file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/5/0xBB2A7A26094c456637E9CcB67BEfEff700C1ba4a/sources/src/Blacklist.sol | checks if address is blacklisted | function isBlacklisted(address account) public view virtual returns (bool) {
return _blacklist[account];
}
| 1,914,054 |
./full_match/80001/0xF8e81B3D2490cb9E9f3A2277Ec7cEDD058131867/sources/contracts/SettingsInternal.sol | Increment Counter / | function _counterUp() internal virtual {
Settings storage s = getSettings();
s.counter += 1;
}
| 5,565,854 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/[email protected]/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/[email protected]/access/Ownable.sol";
import "@openzeppelin/[email protected]/security/ReentrancyGuard.sol";
contract MiniSora is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint;
string internal metadataDirCID;
// This can be the OpenSea URI of the chainrand NFT, which contains
// Chainrand's address and the Chainrand token ID.
// The Chainrand NFT contains all the information to reproduce the
// exact attributes of this generative collection for verification.
string public PROVENANCE;
uint public constant MAX_TOKENS = 32;
uint public constant MAX_TOKENS_PER_MINT = 10;
uint public constant MINT_FEE = 10000000000000000; // 0.01 ETH
/// @dev 1: opened, 255: closed.
uint saleState;
event Revealed(string, string);
constructor() ERC721("Mini Sora", "MSora") {
saleState = 255;
}
/// @dev Mint tokens.
function mint(uint _numTokens) public payable nonReentrant {
require(MINT_FEE * _numTokens <= msg.value, "Insufficient payment.");
require(_numTokens <= MAX_TOKENS_PER_MINT, "Tokens per mint exceeded");
require(_numTokens > 0, "Minimum number to mint is 1.");
require(saleState == 1, "Sale is not opened.");
for (uint i = 0; i < _numTokens; i++) {
uint tokenId = totalSupply();
require(tokenId < MAX_TOKENS, "No more tokens available.");
_safeMint(msg.sender, tokenId);
}
}
/// @dev Mint tokens for the creator.
function selfMint(uint _numTokens) public onlyOwner {
for (uint i = 0; i < _numTokens; i++) {
uint tokenId = totalSupply();
require(tokenId < MAX_TOKENS, "No more tokens available.");
_safeMint(msg.sender, tokenId);
}
}
/// @dev Withdraws Ether for the owner.
function withdraw() public onlyOwner {
uint256 amount = address(this).balance;
payable(msg.sender).transfer(amount);
}
/// @dev Returns the token URI.
function tokenURI(uint _tokenId) override public view returns (string memory) {
require(_tokenId < totalSupply(), "Token not found.");
if (bytes(metadataDirCID).length == 0) {
return "";
}
return string(abi.encodePacked("https://", metadataDirCID,
".ipfs.dweb.link/metadata/", _tokenId.toString(), ".json"));
}
/// @dev Set the metadata directory CID
function reveal(string memory _metadataDirCID, string memory _provenance) public onlyOwner {
metadataDirCID = _metadataDirCID;
PROVENANCE = _provenance;
emit Revealed(_metadataDirCID, _provenance);
}
/// @dev Opens the sale.
function openSale() public onlyOwner {
saleState = 1;
}
/// @dev Closes the sale.
function closeSale() public onlyOwner {
saleState = 255;
}
} | Opens the sale. | function openSale() public onlyOwner {
saleState = 1;
}
| 12,835,370 |
./full_match/80001/0xbB7Bf10aB05d0ed4B351C43197aB2Cbbd86c6abd/sources/contracts/pools/Pool.sol | Adds a new address for redeem fees exemption _address address to be exempted on redeem fees | function addRedeemFeeExemptedAddress(address _address) external virtual {
onlyPoolOwner();
redeemFeeExemptedAddresses[_address] = true;
}
| 9,448,150 |
./full_match/4/0x5e9748Bd1281845Ae3A1fBD7Fa5871978Ed53b3c/sources/TheStripeNFT.sol | public if not eligble for presale or vipgeneral publicpresale | function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
if (whitelisted[msg.sender] != true) {
if (presaleWallets[msg.sender] != true || vips[msg.sender] != true) {
require(msg.value >= cost * _mintAmount);
if (vips[msg.sender] = true) {
require(msg.value >= vipcost * _mintAmount);
}
}
else {
require(msg.value >= presaleCost * _mintAmount);
}
}
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
| 13,298,540 |
/**
*Submitted for verification at Etherscan.io on 2021-10-18
*/
/**
* Copyright 2017-2021, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
// 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);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev 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);
}
/**
* @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 {}
}
/**
* @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");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @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 ERC20Burnable is Context, ERC20 {
/**
* @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 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
contract Upgradeable_0_8 is Ownable {
address public implementation;
}
contract OokiToken is Upgradeable_0_8, ERC20Burnable {
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
constructor() ERC20("Ooki Token", "OOKI") {}
function initialize() public onlyOwner {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("Ooki Token")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function rescue(IERC20 _token) public onlyOwner {
SafeERC20.safeTransfer(_token, msg.sender, _token.balanceOf(address(this)));
}
// constructor does not modify proxy storage
function name() public view override returns (string memory) {
return "Ooki Token";
}
// constructor does not modify proxy storage
function symbol() public view override returns (string memory) {
return "OOKI";
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "OOKI: 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, "OOKI: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
function _beforeTokenTransfer(
address /*from*/,
address to,
uint256 /*amount*/
) internal override {
require(to != address(this), "ERC20: token contract is receiver");
}
} | constructor does not modify proxy storage | function name() public view override returns (string memory) {
return "Ooki Token";
}
| 2,099,125 |
./partial_match/42/0x18e44a480dC802d2b7fe5f128c7997c6f0C23D27/sources/napMigrationPool.sol | Emergency Function to change Migration Status in case of unforseen error | function emergencyMigrationStatusChange(uint _newMigrationStatus) public onlyOwner {
migrationStatus = _newMigrationStatus;
}
| 9,033,474 |
pragma solidity ^0.4.11;
contract ERC20Interface {
// Get the total token supply
function totalSupply() constant returns (uint256);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality
function approve(address _spender, uint256 _value) returns (bool success);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract RoseCoin is ERC20Interface {
uint8 public constant decimals = 5;
string public constant symbol = "RSC";
string public constant name = "RoseCoin";
uint public _level = 0;
bool public _selling = true;
uint public _totalSupply = 10 ** 14;
uint public _originalBuyPrice = 10 ** 10;
uint public _minimumBuyAmount = 10 ** 17;
// Owner of this contract
address public owner;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
uint public _icoSupply = _totalSupply;
uint[4] public ratio = [12, 10, 10, 13];
uint[4] public threshold = [95000000000000, 85000000000000, 0, 80000000000000];
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
modifier onlyNotOwner() {
if (msg.sender == owner) {
revert();
}
_;
}
modifier thresholdAll() {
if (!_selling || msg.value < _minimumBuyAmount || _icoSupply <= threshold[3]) { //
revert();
}
_;
}
// Constructor
function RoseCoin() {
owner = msg.sender;
balances[owner] = _totalSupply;
}
function totalSupply() constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
// Transfer the balance from sender's account to another account
function transfer(address _to, uint256 _amount) returns (bool) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
function toggleSale() onlyOwner {
_selling = !_selling;
}
function setBuyPrice(uint newBuyPrice) onlyOwner {
_originalBuyPrice = newBuyPrice;
}
// Buy RoseCoin by sending Ether
function buy() payable onlyNotOwner thresholdAll returns (uint256 amount) {
amount = 0;
uint remain = msg.value / _originalBuyPrice;
while (remain > 0 && _level < 3) { //
remain = remain * ratio[_level] / ratio[_level+1];
if (_icoSupply <= remain + threshold[_level]) {
remain = (remain + threshold[_level] - _icoSupply) * ratio[_level+1] / ratio[_level];
amount += _icoSupply - threshold[_level];
_icoSupply = threshold[_level];
_level += 1;
}
else {
_icoSupply -= remain;
amount += remain;
remain = 0;
break;
}
}
if (balances[owner] < amount)
revert();
if (remain > 0) {
remain *= _originalBuyPrice;
msg.sender.transfer(remain);
}
balances[owner] -= amount;
balances[msg.sender] += amount;
owner.transfer(msg.value - remain);
Transfer(owner, msg.sender, amount);
return amount;
}
// Owner withdraws Ether in contract
function withdraw() onlyOwner returns (bool) {
return owner.send(this.balance);
}
} | What is the balance of a particular account? | function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
| 2,139,067 |
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol
pragma solidity ^0.5.4;
interface IntVoteInterface {
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier ONLYPROPOSALOWNER208(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
modifier VOTABLE853(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
event NEWPROPOSAL588( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event EXECUTEPROPOSAL706(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VOTEPROPOSAL760( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CANCELPROPOSAL161(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING
event CANCELVOTING574(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING
function PROPOSE661( //inject NONSTANDARD NAMING
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function VOTE536( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function CANCELVOTE202(bytes32 _proposalId) external; //inject NONSTANDARD NAMING
function GETNUMBEROFCHOICES589(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function ISVOTABLE375(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING
function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING
function ISABSTAINALLOW791() external pure returns(bool); //inject NONSTANDARD NAMING
function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
interface IERC20 {
function TRANSFER985(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE946(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM649(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY573() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF995(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE88(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER258(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL578(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
pragma solidity ^0.5.4;
interface VotingMachineCallbacksInterface {
function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function BURNREPUTATION898(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function STAKINGTOKENTRANSFER53(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
returns(bool);
function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED48(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED48(address(0), _owner);
}
function OWNER574() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER824() { //inject NONSTANDARD NAMING
require(ISOWNER625());
_;
}
function ISOWNER625() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP632() public ONLYOWNER824 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED48(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP334(address newOwner) public ONLYOWNER824 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP900(newOwner);
}
function _TRANSFEROWNERSHIP900(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED48(_owner, newOwner);
_owner = newOwner;
}
}
// File: @daostack/infra/contracts/Reputation.sol
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event MINT335(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING
// Event indicating burning of reputation for an address.
event BURN261(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of reputation at a specific block number
uint128 value;
}
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the reputation
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING
return TOTALSUPPLYAT652(block.number);
}
// Query balance and totalSupply in History
function BALANCEOF995(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return BALANCEOFAT780(_owner, block.number);
}
function BALANCEOFAT780(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return GETVALUEAT483(balances[_owner], _blockNumber);
}
}
function TOTALSUPPLYAT652(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return GETVALUEAT483(totalSupplyHistory, _blockNumber);
}
}
function MINT69(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY573();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = BALANCEOF995(_user);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply + _amount);
UPDATEVALUEATNOW719(balances[_user], previousBalanceTo + _amount);
emit MINT335(_user, _amount);
return true;
}
function BURN206(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY573();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = BALANCEOF995(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply - amountBurned);
UPDATEVALUEATNOW719(balances[_user], previousBalanceFrom - amountBurned);
emit BURN261(_user, amountBurned);
return true;
}
// Internal helper functions to query and set a value in a snapshot array
function GETVALUEAT483(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING
if (checkpoints.length == 0) {
return 0;
}
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function UPDATEVALUEATNOW719(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
library SafeMath {
function MUL295(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 DIV1(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 SUB141(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD15(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD36(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF995(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE88(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER985(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER402(msg.sender, to, value);
return true;
}
function APPROVE946(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE913(msg.sender, spender, value);
return true;
}
function TRANSFERFROM649(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER402(from, to, value);
_APPROVE913(from, msg.sender, _allowed[from][msg.sender].SUB141(value));
return true;
}
function INCREASEALLOWANCE616(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].ADD15(addedValue));
return true;
}
function DECREASEALLOWANCE72(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].SUB141(subtractedValue));
return true;
}
function _TRANSFER402(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB141(value);
_balances[to] = _balances[to].ADD15(value);
emit TRANSFER258(from, to, value);
}
function _MINT318(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD15(value);
_balances[account] = _balances[account].ADD15(value);
emit TRANSFER258(address(0), account, value);
}
function _BURN875(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB141(value);
_balances[account] = _balances[account].SUB141(value);
emit TRANSFER258(account, address(0), value);
}
function _APPROVE913(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit APPROVAL578(owner, spender, value);
}
function _BURNFROM507(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_BURN875(account, value);
_APPROVE913(account, msg.sender, _allowed[account][msg.sender].SUB141(value));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
contract ERC20Burnable is ERC20 {
function BURN206(uint256 value) public { //inject NONSTANDARD NAMING
_BURN875(msg.sender, value);
}
function BURNFROM991(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM507(from, value);
}
}
// File: contracts/controller/DAOToken.sol
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals662 = 18; //inject NONSTANDARD NAMING
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function MINT69(address _to, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING
if (cap > 0)
require(TOTALSUPPLY573().ADD15(_amount) <= cap);
_MINT318(_to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.2;
library Address {
function ISCONTRACT51(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: contracts/libs/SafeERC20.sol
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private transfer_selector475 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private transferfrom_selector4 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private approve_selector816 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING
function SAFETRANSFER442(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT51());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transfer_selector475, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFETRANSFERFROM294(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT51());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transferfrom_selector4, _from, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFEAPPROVE771(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT51());
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero.
require((_value == 0) || (IERC20(_erc20Addr).ALLOWANCE88(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(approve_selector816, _spender, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
// File: contracts/controller/Avatar.sol
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GENERICCALL988(address indexed _contract, bytes _data, uint _value, bool _success); //inject NONSTANDARD NAMING
event SENDETHER194(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFER653(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFERFROM913(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENAPPROVAL142(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING
event RECEIVEETHER18(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING
event METADATA150(string _metaData); //inject NONSTANDARD NAMING
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit RECEIVEETHER18(msg.sender, msg.value);
}
function GENERICCALL327(address _contract, bytes memory _data, uint256 _value) //inject NONSTANDARD NAMING
public
ONLYOWNER824
returns(bool success, bytes memory returnValue) {
// solhint-disable-next-line avoid-call-value
(success, returnValue) = _contract.call.value(_value)(_data);
emit GENERICCALL988(_contract, _data, _value, success);
}
function SENDETHER177(uint256 _amountInWei, address payable _to) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING
_to.transfer(_amountInWei);
emit SENDETHER194(_amountInWei, _to);
return true;
}
function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER824 returns(bool)
{
address(_externalToken).SAFETRANSFER442(_to, _value);
emit EXTERNALTOKENTRANSFER653(address(_externalToken), _to, _value);
return true;
}
function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public ONLYOWNER824 returns(bool)
{
address(_externalToken).SAFETRANSFERFROM294(_from, _to, _value);
emit EXTERNALTOKENTRANSFERFROM913(address(_externalToken), _from, _to, _value);
return true;
}
function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER824 returns(bool)
{
address(_externalToken).SAFEAPPROVE771(_spender, _value);
emit EXTERNALTOKENAPPROVAL142(address(_externalToken), _spender, _value);
return true;
}
function METADATA450(string memory _metaData) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING
emit METADATA150(_metaData);
return true;
}
}
// File: contracts/universalSchemes/UniversalSchemeInterface.sol
pragma solidity ^0.5.4;
contract UniversalSchemeInterface {
function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING
}
// File: contracts/globalConstraints/GlobalConstraintInterface.sol
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function PRE222( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function POST74( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function WHEN422() public returns(CallPhase); //inject NONSTANDARD NAMING
}
// File: contracts/controller/ControllerInterface.sol
pragma solidity ^0.5.4;
interface ControllerInterface {
function MINTREPUTATION981(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function BURNREPUTATION898(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function MINTTOKENS758(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function REGISTERSCHEME37(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSCHEME785(address _scheme, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSELF96(address _avatar) external returns(bool); //inject NONSTANDARD NAMING
function ADDGLOBALCONSTRAINT638(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function REMOVEGLOBALCONSTRAINT28 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function UPGRADECONTROLLER721(address _newController, Avatar _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function GENERICCALL327(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) //inject NONSTANDARD NAMING
external
returns(bool, bytes memory);
function SENDETHER177(uint256 _amountInWei, address payable _to, Avatar _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function METADATA450(string calldata _metaData, Avatar _avatar) external returns(bool); //inject NONSTANDARD NAMING
function GETNATIVEREPUTATION762(address _avatar) //inject NONSTANDARD NAMING
external
view
returns(address);
function ISSCHEMEREGISTERED658( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
function GETSCHEMEPARAMETERS578(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETGLOBALCONSTRAINTPARAMETERS702(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETSCHEMEPERMISSIONS800(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING
function GLOBALCONSTRAINTSCOUNT83(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING
function ISGLOBALCONSTRAINTREGISTERED605(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
}
// File: contracts/universalSchemes/UniversalScheme.sol
pragma solidity ^0.5.4;
contract UniversalScheme is UniversalSchemeInterface {
function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING
require(ControllerInterface(_avatar.OWNER574()).ISSCHEMEREGISTERED658(address(this), address(_avatar)),
"scheme is not registered");
return ControllerInterface(_avatar.OWNER574()).GETSCHEMEPARAMETERS578(address(this), address(_avatar));
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
pragma solidity ^0.5.2;
library ECDSA {
function RECOVER336(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
function TOETHSIGNEDMESSAGEHASH747(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: @daostack/infra/contracts/libs/RealMath.sol
pragma solidity ^0.5.4;
library RealMath {
uint256 constant private real_bits978 = 256; //inject NONSTANDARD NAMING
uint256 constant private real_fbits102 = 40; //inject NONSTANDARD NAMING
uint256 constant private real_one722 = uint256(1) << real_fbits102; //inject NONSTANDARD NAMING
function POW948(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
// Start with the 0th power
uint256 realResult = real_one722;
while (tempExponent != 0) {
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
realResult = MUL295(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
if (tempExponent != 0) {
// Do the squaring
tempRealBase = MUL295(tempRealBase, tempRealBase);
}
}
// Return the final result.
return realResult;
}
function FRACTION401(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV1(uint256(numerator) * real_one722, uint256(denominator) * real_one722);
}
function MUL295(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
uint256 res = realA * realB;
require(res/realA == realB, "RealMath mul overflow");
return (res >> real_fbits102);
}
function DIV1(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return uint256((uint256(realNumerator) * real_one722) / uint256(realDenominator));
}
}
// File: @daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol
pragma solidity ^0.5.4;
interface ProposalExecuteInterface {
function EXECUTEPROPOSAL422(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.2;
library Math {
function MAX135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN317(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE86(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol
pragma solidity ^0.5.4;
contract GenesisProtocolLogic is IntVoteInterface {
using SafeMath for uint256;
using Math for uint256;
using RealMath for uint216;
using RealMath for uint256;
using Address for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
//Organization's parameters
struct Parameters {
uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar.
uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode.
uint256 preBoostedVotePeriodLimit; //the time limit for a proposal
//to be in an preparation state (stable) before boosted.
uint256 thresholdConst; //constant for threshold calculation .
//threshold =thresholdConst ** (numberOfBoostedProposals)
uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals
//in the threshold calculation to prevent overflow
uint256 quietEndingPeriod; //quite ending period
uint256 proposingRepReward;//proposer reputation reward.
uint256 votersReputationLossRatio;//Unsuccessful pre booster
//voters lose votersReputationLossRatio% of their reputation.
uint256 minimumDaoBounty;
uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula
//(daoBountyConst * averageBoostDownstakes)/100 .
uint256 activationTime;//the point in time after which proposals can be created.
//if this address is set so only this address is allowed to vote of behalf of someone else.
address voteOnBehalf;
}
struct Voter {
uint256 vote; // YES(1) ,NO(2)
uint256 reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint256 vote; // YES(1) ,NO(2)
uint256 amount; // amount of staker's stake
uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation.
}
struct Proposal {
bytes32 organizationId; // the organization unique identifier the proposal is target to.
address callbacks; // should fulfill voting callbacks interface.
ProposalState state;
uint256 winningVote; //the winning vote.
address proposer;
//the proposal boosted period limit . it is updated for the case of quiteWindow mode.
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time.
uint256 daoBounty;
uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers.
uint256 confidenceThreshold;
//The percentage from upper stakes which the caller for the expiration was given.
uint256 expirationCallBountyPercentage;
uint[3] times; //times[0] - submittedTime
//times[1] - boostedPhaseTime
//times[2] -preBoostedPhaseTime;
bool daoRedeemItsWinnings;
// vote reputation
mapping(uint256 => uint256 ) votes;
// vote reputation
mapping(uint256 => uint256 ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint256 => uint256 ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event STAKE754(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event REDEEM636(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMDAOBOUNTY578(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMREPUTATION314(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event STATECHANGE374(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING
event GPEXECUTEPROPOSAL538(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING
event EXPIRATIONCALLBOUNTY93(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING
event CONFIDENCELEVELCHANGE532(bytes32 indexed _proposalId, uint256 _confidenceThreshold); //inject NONSTANDARD NAMING
mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters
mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself.
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
//organizationId => organization
mapping(bytes32 => address ) public organizations;
//organizationId => averageBoostDownstakes
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public num_of_choices613 = 2; //inject NONSTANDARD NAMING
uint256 constant public no391 = 2; //inject NONSTANDARD NAMING
uint256 constant public yes596 = 1; //inject NONSTANDARD NAMING
uint256 public proposalsCnt; // Total number of proposals
IERC20 public stakingToken;
address constant private gen_token_address929 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING
uint256 constant private max_boosted_proposals645 = 4096; //inject NONSTANDARD NAMING
constructor(IERC20 _stakingToken) public {
//The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS .
//This will work for a network which already hosted the GEN token on this address (e.g mainnet).
//If such contract address does not exist in the network (e.g ganache)
//the contract will use the _stakingToken param as the
//staking token address.
if (address(gen_token_address929).ISCONTRACT51()) {
stakingToken = IERC20(gen_token_address929);
} else {
stakingToken = _stakingToken;
}
}
modifier VOTABLE853(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(_ISVOTABLE722(_proposalId));
_;
}
function PROPOSE661(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING
external
returns(bytes32)
{
// solhint-disable-next-line not-rely-on-time
require(now > parameters[_paramsHash].activationTime, "not active yet");
//Check parameters existence.
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.ADD15(1);
// Open proposal:
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
// solhint-disable-next-line not-rely-on-time
proposal.times[0] = now;//submitted time
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = no391;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
//calc dao bounty
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.MUL295(averagesDownstakesOfBoosted[proposal.organizationId]).DIV1(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[no391] = proposal.daoBountyRemain;//dao downstake on the proposal
emit NEWPROPOSAL588(proposalId, organizations[proposal.organizationId], num_of_choices613, _proposer, _paramsHash);
return proposalId;
}
function EXECUTEBOOSTED17(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndingPeriod");
require(_EXECUTE501(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
// solhint-disable-next-line not-rely-on-time
(uint(1).ADD15(now.SUB141(proposal.currentBoostedVotePeriodLimit.ADD15(proposal.times[1])).DIV1(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100);
require(stakingToken.TRANSFER985(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit EXPIRATIONCALLBOUNTY93(_proposalId, msg.sender, expirationCallBounty);
}
function SETPARAMETERS600( //inject NONSTANDARD NAMING
uint[11] calldata _params, //use array here due to stack too deep issue.
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = GETPARAMETERSHASH529(_params, _voteOnBehalf);
//set a limit for power for a given alpha to prevent overflow
uint256 limitExponent = 172;//for alpha less or equal 2
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).FRACTION401(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
// solhint-disable-next-line function-max-lines,code-complexity
function REDEEM641(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == yes596) {
lostReputation = proposal.preBoostedVotes[no391];
} else {
lostReputation = proposal.preBoostedVotes[yes596];
}
lostReputation = (lostReputation.MUL295(params.votersReputationLossRatio))/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
uint256 totalStakes = proposal.stakes[no391].ADD15(proposal.stakes[yes596]);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
if (staker.amount > 0) {
uint256 totalStakesLeftAfterCallBounty =
totalStakes.SUB141(proposal.expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100));
if (proposal.state == ProposalState.ExpiredInQueue) {
//Stakes of a proposal that expires in Queue are sent back to stakers
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
if (staker.vote == yes596) {
if (proposal.daoBounty < totalStakesLeftAfterCallBounty) {
uint256 _totalStakes = totalStakesLeftAfterCallBounty.SUB141(proposal.daoBounty);
rewards[0] = (staker.amount.MUL295(_totalStakes))/totalWinningStakes;
}
} else {
rewards[0] = (staker.amount.MUL295(totalStakesLeftAfterCallBounty))/totalWinningStakes;
}
}
staker.amount = 0;
}
//dao redeem its winnings
if (proposal.daoRedeemItsWinnings == false &&
_beneficiary == organizations[proposal.organizationId] &&
proposal.state != ProposalState.ExpiredInQueue &&
proposal.winningVote == no391) {
rewards[0] =
rewards[0].ADD15((proposal.daoBounty.MUL295(totalStakes))/totalWinningStakes).SUB141(proposal.daoBounty);
proposal.daoRedeemItsWinnings = true;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//give back reputation for the voter
rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100)
.ADD15((voter.reputation.MUL295(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]);
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes596)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.SUB141(rewards[0]);
require(stakingToken.TRANSFER985(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit REDEEM636(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].ADD15(rewards[2]) != 0) {
VotingMachineCallbacksInterface(proposal.callbacks)
.MINTREPUTATION981(rewards[1].ADD15(rewards[2]), _beneficiary, _proposalId);
emit REDEEMREPUTATION314(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].ADD15(rewards[2])
);
}
}
function REDEEMDAOBOUNTY8(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == yes596)&&
(totalWinningStakes != 0)) {
//as staker
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(VotingMachineCallbacksInterface(proposal.callbacks)
.BALANCEOFSTAKINGTOKEN878(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.SUB141(potentialAmount);
require(
VotingMachineCallbacksInterface(proposal.callbacks)
.STAKINGTOKENTRANSFER53(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit REDEEMDAOBOUNTY578(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function SHOULDBOOST603(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING
Proposal memory proposal = proposals[_proposalId];
return (_SCORE635(_proposalId) > THRESHOLD53(proposal.paramsHash, proposal.organizationId));
}
function THRESHOLD53(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.POW948(power);
}
function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING
uint[11] memory _params,//use array here due to stack too deep issue.
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
//double call to keccak256 to avoid deep stack issue when call with too many params.
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
// solhint-disable-next-line function-max-lines,code-complexity
function _EXECUTE501(bytes32 _proposalId) internal VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
VotingMachineCallbacksInterface(proposal.callbacks).GETTOTALREPUTATIONSUPPLY50(_proposalId);
//first divide by 100 to prevent overflow
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = no391;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId);
if (_SCORE635(_proposalId) > confidenceThreshold) {
//change proposal mode to PreBoosted mode.
proposal.state = ProposalState.PreBoosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId);
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_SCORE635(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals645)) {
//change proposal mode to Boosted mode.
proposal.state = ProposalState.Boosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
//add a value to average -> average = average + ((value - average) / nbValues)
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
// solium-disable-next-line indentation
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[no391])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else { //check the Confidence level is stable
uint256 proposalScore = _SCORE635(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.MIN317(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
emit CONFIDENCELEVELCHANGE532(_proposalId, confidenceThreshold);
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].SUB141(1);
//remove a value from average = ((average * nbValues) - value) / (nbValues - 1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.MUL295(boostedProposals+1).SUB141(proposal.stakes[no391]))/boostedProposals;
}
}
emit EXECUTEPROPOSAL706(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPEXECUTEPROPOSAL538(_proposalId, executionState);
ProposalExecuteInterface(proposal.callbacks).EXECUTEPROPOSAL422(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit STATECHANGE374(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _STAKE234(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING
// 0 is not a valid vote.
require(_vote <= num_of_choices613 && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_EXECUTE501(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
// enable to increase stake only on the previous stake vote
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.TRANSFERFROM649(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.ADD15(amount); //update totalRedeemableStakes
staker.amount = staker.amount.ADD15(amount);
//This is to prevent average downstakes calculation overflow
//Note that any how GEN cap is 100000000 ether.
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == yes596) {
staker.amount4Bounty = staker.amount4Bounty.ADD15(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.ADD15(proposal.stakes[_vote]);
emit STAKE754(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _EXECUTE501(_proposalId);
}
// solhint-disable-next-line function-max-lines,code-complexity
function INTERNALVOTE757(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING
require(_vote <= num_of_choices613 && _vote > 0, "0 < _vote <= 2");
if (_EXECUTE501(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).REPUTATIONOF984(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
// If this voter has already voted, return false.
if (proposal.voters[_voter].reputation != 0) {
return false;
}
// The voting itself:
proposal.votes[_vote] = rep.ADD15(proposal.votes[_vote]);
//check if the current winningVote changed or there is a tie.
//for the case there is a tie the current winningVote set to NO.
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[no391] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == yes596)) {
if (proposal.state == ProposalState.Boosted &&
// solhint-disable-next-line not-rely-on-time
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
//quietEndingPeriod
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.ADD15(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.MUL295(rep))/100;
VotingMachineCallbacksInterface(proposal.callbacks).BURNREPUTATION898(reputationDeposit, _voter, _proposalId);
}
emit VOTEPROPOSAL760(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _EXECUTE501(_proposalId);
}
function _SCORE635(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
//proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal.
return uint216(proposal.stakes[yes596]).FRACTION401(uint216(proposal.stakes[no391]));
}
function _ISVOTABLE722(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
// File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol
pragma solidity ^0.5.4;
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic {
using ECDSA for bytes32;
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant delegation_hash_eip712291 = //inject NONSTANDARD NAMING
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce; //stakes Nonce
constructor(IERC20 _stakingToken)
public
// solhint-disable-next-line no-empty-blocks
GenesisProtocolLogic(_stakingToken) {
}
function STAKE53(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING
return _STAKE234(_proposalId, _vote, _amount, msg.sender);
}
function STAKEWITHSIGNATURE42( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
delegation_hash_eip712291, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).TOETHSIGNEDMESSAGEHASH747();
}
address staker = delegationDigest.RECOVER336(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].ADD15(1);
return _STAKE234(_proposalId, _vote, _amount, staker);
}
function VOTE536(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING
external
VOTABLE853(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return INTERNALVOTE757(_proposalId, voter, _vote, _amount);
}
function CANCELVOTE202(bytes32 _proposalId) external VOTABLE853(_proposalId) { //inject NONSTANDARD NAMING
//this is not allowed
return;
}
function EXECUTE916(bytes32 _proposalId) external VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
return _EXECUTE501(_proposalId);
}
function GETNUMBEROFCHOICES589(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING
return num_of_choices613;
}
function GETPROPOSALTIMES314(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING
return proposals[_proposalId].times;
}
function VOTEINFO167(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].votes[_choice];
}
function ISVOTABLE375(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING
return _ISVOTABLE722(_proposalId);
}
function PROPOSALSTATUS186(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING
return (
proposals[_proposalId].preBoostedVotes[yes596],
proposals[_proposalId].preBoostedVotes[no391],
proposals[_proposalId].stakes[yes596],
proposals[_proposalId].stakes[no391]
);
}
function GETPROPOSALORGANIZATION49(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].organizationId);
}
function GETSTAKER814(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function VOTESTAKE56(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].stakes[_vote];
}
function WINNINGVOTE889(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].winningVote;
}
function STATE293(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING
return proposals[_proposalId].state;
}
function ISABSTAINALLOW791() external pure returns(bool) { //inject NONSTANDARD NAMING
return false;
}
function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING
return (yes596, no391);
}
function SCORE81(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING
return _SCORE635(_proposalId);
}
}
// File: contracts/votingMachines/VotingMachineCallbacks.sol
pragma solidity ^0.5.4;
contract VotingMachineCallbacks is VotingMachineCallbacksInterface {
struct ProposalInfo {
uint256 blockNumber; // the proposal's block number
Avatar avatar; // the proposal's avatar
}
modifier ONLYVOTINGMACHINE284(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine");
_;
}
// VotingMaching -> proposalId -> ProposalInfo
mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo;
function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE284(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.OWNER574()).MINTREPUTATION981(_amount, _beneficiary, address(avatar));
}
function BURNREPUTATION898(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE284(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.OWNER574()).BURNREPUTATION898(_amount, _beneficiary, address(avatar));
}
function STAKINGTOKENTRANSFER53( //inject NONSTANDARD NAMING
IERC20 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
ONLYVOTINGMACHINE284(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.OWNER574()).EXTERNALTOKENTRANSFER167(_stakingToken, _beneficiary, _amount, avatar);
}
function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) {
return 0;
}
return _stakingToken.BALANCEOF995(address(avatar));
}
function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().TOTALSUPPLYAT652(proposal.blockNumber);
}
function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().BALANCEOFAT780(_owner, proposal.blockNumber);
}
}
// File: contracts/universalSchemes/SchemeRegistrar.sol
pragma solidity ^0.5.4;
contract SchemeRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface {
event NEWSCHEMEPROPOSAL971( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
address _scheme,
bytes32 _parametersHash,
bytes4 _permissions,
string _descriptionHash
);
event REMOVESCHEMEPROPOSAL965(address indexed _avatar, //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
address _scheme,
string _descriptionHash
);
event PROPOSALEXECUTED934(address indexed _avatar, bytes32 indexed _proposalId, int256 _param); //inject NONSTANDARD NAMING
event PROPOSALDELETED307(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING
// a SchemeProposal is a proposal to add or remove a scheme to/from the an organization
struct SchemeProposal {
address scheme; //
bool addScheme; // true: add a scheme, false: remove a scheme.
bytes32 parametersHash;
bytes4 permissions;
}
// A mapping from the organization (Avatar) address to the saved data of the organization:
mapping(address=>mapping(bytes32=>SchemeProposal)) public organizationsProposals;
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
struct Parameters {
bytes32 voteRegisterParams;
bytes32 voteRemoveParams;
IntVoteInterface intVote;
}
mapping(bytes32=>Parameters) public parameters;
function EXECUTEPROPOSAL422(bytes32 _proposalId, int256 _param) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.scheme != address(0));
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED307(address(avatar), _proposalId);
if (_param == 1) {
// Define controller and get the params:
ControllerInterface controller = ControllerInterface(avatar.OWNER574());
// Add a scheme:
if (proposal.addScheme) {
require(controller.REGISTERSCHEME37(
proposal.scheme,
proposal.parametersHash,
proposal.permissions,
address(avatar))
);
}
// Remove a scheme:
if (!proposal.addScheme) {
require(controller.UNREGISTERSCHEME785(proposal.scheme, address(avatar)));
}
}
emit PROPOSALEXECUTED934(address(avatar), _proposalId, _param);
return true;
}
function SETPARAMETERS600( //inject NONSTANDARD NAMING
bytes32 _voteRegisterParams,
bytes32 _voteRemoveParams,
IntVoteInterface _intVote
) public returns(bytes32)
{
bytes32 paramsHash = GETPARAMETERSHASH529(_voteRegisterParams, _voteRemoveParams, _intVote);
parameters[paramsHash].voteRegisterParams = _voteRegisterParams;
parameters[paramsHash].voteRemoveParams = _voteRemoveParams;
parameters[paramsHash].intVote = _intVote;
return paramsHash;
}
function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING
bytes32 _voteRegisterParams,
bytes32 _voteRemoveParams,
IntVoteInterface _intVote
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteRegisterParams, _voteRemoveParams, _intVote));
}
function PROPOSESCHEME503( //inject NONSTANDARD NAMING
Avatar _avatar,
address _scheme,
bytes32 _parametersHash,
bytes4 _permissions,
string memory _descriptionHash
)
public
returns(bytes32)
{
// propose
require(_scheme != address(0), "scheme cannot be zero");
Parameters memory controllerParams = parameters[GETPARAMETERSFROMCONTROLLER560(_avatar)];
bytes32 proposalId = controllerParams.intVote.PROPOSE661(
2,
controllerParams.voteRegisterParams,
msg.sender,
address(_avatar)
);
SchemeProposal memory proposal = SchemeProposal({
scheme: _scheme,
parametersHash: _parametersHash,
addScheme: true,
permissions: _permissions
});
emit NEWSCHEMEPROPOSAL971(
address(_avatar),
proposalId,
address(controllerParams.intVote),
_scheme, _parametersHash,
_permissions,
_descriptionHash
);
organizationsProposals[address(_avatar)][proposalId] = proposal;
proposalsInfo[address(controllerParams.intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
return proposalId;
}
function PROPOSETOREMOVESCHEME279(Avatar _avatar, address _scheme, string memory _descriptionHash) //inject NONSTANDARD NAMING
public
returns(bytes32)
{
require(_scheme != address(0), "scheme cannot be zero");
bytes32 paramsHash = GETPARAMETERSFROMCONTROLLER560(_avatar);
Parameters memory params = parameters[paramsHash];
IntVoteInterface intVote = params.intVote;
bytes32 proposalId = intVote.PROPOSE661(2, params.voteRemoveParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId].scheme = _scheme;
emit REMOVESCHEMEPROPOSAL965(address(_avatar), proposalId, address(intVote), _scheme, _descriptionHash);
proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
return proposalId;
}
}
| inject NONSTANDARD NAMING | function FRACTION401(uint216 numerator, uint216 denominator) internal pure returns (uint256) { | 15,855,754 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.13;
import "./libraries/SafeMath.sol";
import "./libraries/SafeERC20.sol";
import "./interfaces/IOwnable.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IERC20Metadata.sol";
import "./interfaces/IOHM.sol";
import "./interfaces/IsOHM.sol";
import "./interfaces/IBondingCalculator.sol";
import "./interfaces/ITreasury.sol";
import "./types/OlympusAccessControlled.sol";
contract OlympusTreasury is OlympusAccessControlled, ITreasury {
/* ========== DEPENDENCIES ========== */
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== EVENTS ========== */
event Deposit(address indexed token, uint256 amount, uint256 value);
event Withdrawal(address indexed token, uint256 amount, uint256 value);
event CreateDebt(
address indexed debtor,
address indexed token,
uint256 amount,
uint256 value
);
event RepayDebt(
address indexed debtor,
address indexed token,
uint256 amount,
uint256 value
);
event Managed(address indexed token, uint256 amount);
event ReservesAudited(uint256 indexed totalReserves);
event Minted(
address indexed caller,
address indexed recipient,
uint256 amount
);
event PermissionQueued(STATUS indexed status, address queued);
event Permissioned(address addr, STATUS indexed status, bool result);
/* ========== DATA STRUCTURES ========== */
enum STATUS {
RESERVEDEPOSITOR,
RESERVESPENDER,
RESERVETOKEN,
RESERVEMANAGER,
LIQUIDITYDEPOSITOR,
LIQUIDITYTOKEN,
LIQUIDITYMANAGER,
RESERVEDEBTOR,
REWARDMANAGER,
SOHM,
OHMDEBTOR
}
struct Queue {
STATUS managing;
address toPermit;
address calculator;
uint256 timelockEnd;
bool nullify;
bool executed;
}
/* ========== STATE VARIABLES ========== */
IOHM public immutable OHM;
IsOHM public sOHM;
mapping(STATUS => address[]) public registry;
mapping(STATUS => mapping(address => bool)) public permissions;
mapping(address => address) public bondCalculator;
mapping(address => uint256) public debtLimit;
uint256 public totalReserves;
uint256 public totalDebt;
uint256 public ohmDebt;
Queue[] public permissionQueue;
uint256 public immutable blocksNeededForQueue;
bool public timelockEnabled;
bool public initialized;
uint256 public onChainGovernanceTimelock;
string internal notAccepted = "Treasury: not accepted";
string internal notApproved = "Treasury: not approved";
string internal invalidToken = "Treasury: invalid token";
string internal insufficientReserves = "Treasury: insufficient reserves";
/* ========== CONSTRUCTOR ========== */
constructor(
address _ohm,
uint256 _timelock,
address _authority
) OlympusAccessControlled(IOlympusAuthority(_authority)) {
require(_ohm != address(0), "Zero address: OHM");
OHM = IOHM(_ohm);
timelockEnabled = false;
initialized = false;
blocksNeededForQueue = _timelock;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice allow approved address to deposit an asset for OHM
* @param _amount uint256
* @param _token address
* @param _profit uint256
* @return send_ uint256
*/
function deposit(
uint256 _amount,
address _token,
uint256 _profit
) external override returns (uint256 send_) {
if (permissions[STATUS.RESERVETOKEN][_token]) {
require(permissions[STATUS.RESERVEDEPOSITOR][msg.sender], notApproved);
} else if (permissions[STATUS.LIQUIDITYTOKEN][_token]) {
require(permissions[STATUS.LIQUIDITYDEPOSITOR][msg.sender], notApproved);
} else {
revert(invalidToken);
}
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
uint256 value = tokenValue(_token, _amount);
// mint OHM needed and store amount of rewards for distribution
send_ = value.sub(_profit);
OHM.mint(msg.sender, send_);
totalReserves = totalReserves.add(value);
emit Deposit(_token, _amount, value);
}
/**
* @notice allow approved address to burn OHM for reserves
* @param _amount uint256
* @param _token address
*/
function withdraw(uint256 _amount, address _token) external override {
require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); // Only reserves can be used for redemptions
require(permissions[STATUS.RESERVESPENDER][msg.sender], notApproved);
uint256 value = tokenValue(_token, _amount);
OHM.burnFrom(msg.sender, value);
totalReserves = totalReserves.sub(value);
IERC20(_token).safeTransfer(msg.sender, _amount);
emit Withdrawal(_token, _amount, value);
}
/**
* @notice allow approved address to withdraw assets
* @param _token address
* @param _amount uint256
*/
function manage(address _token, uint256 _amount) external override {
if (permissions[STATUS.LIQUIDITYTOKEN][_token]) {
require(permissions[STATUS.LIQUIDITYMANAGER][msg.sender], notApproved);
} else {
require(permissions[STATUS.RESERVEMANAGER][msg.sender], notApproved);
}
if (
permissions[STATUS.RESERVETOKEN][_token] ||
permissions[STATUS.LIQUIDITYTOKEN][_token]
) {
uint256 value = tokenValue(_token, _amount);
require(value <= excessReserves(), insufficientReserves);
totalReserves = totalReserves.sub(value);
}
IERC20(_token).safeTransfer(msg.sender, _amount);
emit Managed(_token, _amount);
}
/**
* @notice mint new OHM using excess reserves
* @param _recipient address
* @param _amount uint256
*/
function mint(address _recipient, uint256 _amount) external override {
require(permissions[STATUS.REWARDMANAGER][msg.sender], notApproved);
require(_amount <= excessReserves(), insufficientReserves);
OHM.mint(_recipient, _amount);
emit Minted(msg.sender, _recipient, _amount);
}
/**
* DEBT: The debt functions allow approved addresses to borrow treasury assets
* or OHM from the treasury, using sOHM as collateral. This might allow an
* sOHM holder to provide OHM liquidity without taking on the opportunity cost
* of unstaking, or alter their backing without imposing risk onto the treasury.
* Many of these use cases are yet to be defined, but they appear promising.
* However, we urge the community to think critically and move slowly upon
* proposals to acquire these permissions.
*/
/**
* @notice allow approved address to borrow reserves
* @param _amount uint256
* @param _token address
*/
function incurDebt(uint256 _amount, address _token) external override {
uint256 value;
if (_token == address(OHM)) {
require(permissions[STATUS.OHMDEBTOR][msg.sender], notApproved);
value = _amount;
} else {
require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved);
require(permissions[STATUS.RESERVETOKEN][_token], notAccepted);
value = tokenValue(_token, _amount);
}
require(value != 0, invalidToken);
sOHM.changeDebt(value, msg.sender, true);
require(
sOHM.debtBalances(msg.sender) <= debtLimit[msg.sender],
"Treasury: exceeds limit"
);
totalDebt = totalDebt.add(value);
if (_token == address(OHM)) {
OHM.mint(msg.sender, value);
ohmDebt = ohmDebt.add(value);
} else {
totalReserves = totalReserves.sub(value);
IERC20(_token).safeTransfer(msg.sender, _amount);
}
emit CreateDebt(msg.sender, _token, _amount, value);
}
/**
* @notice allow approved address to repay borrowed reserves with reserves
* @param _amount uint256
* @param _token address
*/
function repayDebtWithReserve(uint256 _amount, address _token)
external
override
{
require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved);
require(permissions[STATUS.RESERVETOKEN][_token], notAccepted);
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
uint256 value = tokenValue(_token, _amount);
sOHM.changeDebt(value, msg.sender, false);
totalDebt = totalDebt.sub(value);
totalReserves = totalReserves.add(value);
emit RepayDebt(msg.sender, _token, _amount, value);
}
/**
* @notice allow approved address to repay borrowed reserves with OHM
* @param _amount uint256
*/
function repayDebtWithOHM(uint256 _amount) external {
require(
permissions[STATUS.RESERVEDEBTOR][msg.sender] ||
permissions[STATUS.OHMDEBTOR][msg.sender],
notApproved
);
OHM.burnFrom(msg.sender, _amount);
sOHM.changeDebt(_amount, msg.sender, false);
totalDebt = totalDebt.sub(_amount);
ohmDebt = ohmDebt.sub(_amount);
emit RepayDebt(msg.sender, address(OHM), _amount, _amount);
}
/* ========== MANAGERIAL FUNCTIONS ========== */
/**
* @notice takes inventory of all tracked assets
* @notice always consolidate to recognized reserves before audit
*/
function auditReserves() external onlyGovernor {
uint256 reserves;
address[] memory reserveToken = registry[STATUS.RESERVETOKEN];
for (uint256 i = 0; i < reserveToken.length; i++) {
if (permissions[STATUS.RESERVETOKEN][reserveToken[i]]) {
reserves = reserves.add(
tokenValue(
reserveToken[i],
IERC20(reserveToken[i]).balanceOf(address(this))
)
);
}
}
address[] memory liquidityToken = registry[STATUS.LIQUIDITYTOKEN];
for (uint256 i = 0; i < liquidityToken.length; i++) {
if (permissions[STATUS.LIQUIDITYTOKEN][liquidityToken[i]]) {
reserves = reserves.add(
tokenValue(
liquidityToken[i],
IERC20(liquidityToken[i]).balanceOf(address(this))
)
);
}
}
totalReserves = reserves;
emit ReservesAudited(reserves);
}
/**
* @notice set max debt for address
* @param _address address
* @param _limit uint256
*/
function setDebtLimit(address _address, uint256 _limit)
external
onlyGovernor
{
debtLimit[_address] = _limit;
}
/**
* @notice enable permission from queue
* @param _status STATUS
* @param _address address
* @param _calculator address
*/
function enable(
STATUS _status,
address _address,
address _calculator
) external onlyGovernor {
require(timelockEnabled == false, "Use queueTimelock");
if (_status == STATUS.SOHM) {
sOHM = IsOHM(_address);
} else {
permissions[_status][_address] = true;
if (_status == STATUS.LIQUIDITYTOKEN) {
bondCalculator[_address] = _calculator;
}
(bool registered, ) = indexInRegistry(_address, _status);
if (!registered) {
registry[_status].push(_address);
if (
_status == STATUS.LIQUIDITYTOKEN || _status == STATUS.RESERVETOKEN
) {
(bool reg, uint256 index) = indexInRegistry(_address, _status);
if (reg) {
delete registry[_status][index];
}
}
}
}
emit Permissioned(_address, _status, true);
}
/**
* @notice disable permission from address
* @param _status STATUS
* @param _toDisable address
*/
function disable(STATUS _status, address _toDisable) external {
require(
msg.sender == authority.governor() || msg.sender == authority.guardian(),
"Only governor or guardian"
);
permissions[_status][_toDisable] = false;
emit Permissioned(_toDisable, _status, false);
}
/**
* @notice check if registry contains address
* @return (bool, uint256)
*/
function indexInRegistry(address _address, STATUS _status)
public
view
returns (bool, uint256)
{
address[] memory entries = registry[_status];
for (uint256 i = 0; i < entries.length; i++) {
if (_address == entries[i]) {
return (true, i);
}
}
return (false, 0);
}
/* ========== TIMELOCKED FUNCTIONS ========== */
// functions are used prior to enabling on-chain governance
/**
* @notice queue address to receive permission
* @param _status STATUS
* @param _address address
* @param _calculator address
*/
function queueTimelock(
STATUS _status,
address _address,
address _calculator
) external onlyGovernor {
require(_address != address(0));
require(timelockEnabled == true, "Timelock is disabled, use enable");
uint256 timelock = block.number.add(blocksNeededForQueue);
if (
_status == STATUS.RESERVEMANAGER || _status == STATUS.LIQUIDITYMANAGER
) {
timelock = block.number.add(blocksNeededForQueue.mul(2));
}
permissionQueue.push(
Queue({
managing: _status,
toPermit: _address,
calculator: _calculator,
timelockEnd: timelock,
nullify: false,
executed: false
})
);
emit PermissionQueued(_status, _address);
}
/**
* @notice enable queued permission
* @param _index uint256
*/
function execute(uint256 _index) external {
require(timelockEnabled == true, "Timelock is disabled, use enable");
Queue memory info = permissionQueue[_index];
require(!info.nullify, "Action has been nullified");
require(!info.executed, "Action has already been executed");
require(block.number >= info.timelockEnd, "Timelock not complete");
if (info.managing == STATUS.SOHM) {
// 9
sOHM = IsOHM(info.toPermit);
} else {
permissions[info.managing][info.toPermit] = true;
if (info.managing == STATUS.LIQUIDITYTOKEN) {
bondCalculator[info.toPermit] = info.calculator;
}
(bool registered, ) = indexInRegistry(info.toPermit, info.managing);
if (!registered) {
registry[info.managing].push(info.toPermit);
if (info.managing == STATUS.LIQUIDITYTOKEN) {
(bool reg, uint256 index) = indexInRegistry(
info.toPermit,
STATUS.RESERVETOKEN
);
if (reg) {
delete registry[STATUS.RESERVETOKEN][index];
}
} else if (info.managing == STATUS.RESERVETOKEN) {
(bool reg, uint256 index) = indexInRegistry(
info.toPermit,
STATUS.LIQUIDITYTOKEN
);
if (reg) {
delete registry[STATUS.LIQUIDITYTOKEN][index];
}
}
}
}
permissionQueue[_index].executed = true;
emit Permissioned(info.toPermit, info.managing, true);
}
/**
* @notice cancel timelocked action
* @param _index uint256
*/
function nullify(uint256 _index) external onlyGovernor {
permissionQueue[_index].nullify = true;
}
/**
* @notice disables timelocked functions
*/
function disableTimelock() external onlyGovernor {
require(timelockEnabled == true, "timelock already disabled");
if (
onChainGovernanceTimelock != 0 &&
onChainGovernanceTimelock <= block.number
) {
timelockEnabled = false;
} else {
onChainGovernanceTimelock = block.number.add(blocksNeededForQueue.mul(7)); // 7-day timelock
}
}
/**
* @notice enables timelocks after initilization
*/
function initialize() external onlyGovernor {
require(initialized == false, "Already initialized");
timelockEnabled = true;
initialized = true;
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice returns excess reserves not backing tokens
* @return uint
*/
function excessReserves() public view override returns (uint256) {
return totalReserves.sub(OHM.totalSupply().sub(totalDebt));
}
/**
* @notice returns OHM valuation of asset
* @param _token address
* @param _amount uint256
* @return value_ uint256
*/
function tokenValue(address _token, uint256 _amount)
public
view
override
returns (uint256 value_)
{
value_ = _amount.mul(10**IERC20Metadata(address(OHM)).decimals()).div(
10**IERC20Metadata(_token).decimals()
);
if (permissions[STATUS.LIQUIDITYTOKEN][_token]) {
value_ = IBondingCalculator(bondCalculator[_token]).valuation(
_token,
_amount
);
}
}
/**
* @notice returns supply metric that cannot be manipulated by debt
* @dev use this any time you need to query supply
* @return uint256
*/
function baseSupply() external view override returns (uint256) {
return OHM.totalSupply() - ohmDebt;
}
}
| enables timelocks after initilization/ | function initialize() external onlyGovernor {
require(initialized == false, "Already initialized");
timelockEnabled = true;
initialized = true;
}
| 14,115,770 |
./full_match/1/0x46066a922815B1c9aDF6485daf811BcF631dC330/sources/browser/TriangularArbitrageProduction.sol | l r1amount997/(r01000 + amount997) | function swapTokens(uint amount, uint reserve0, uint reserve1) private pure returns (uint)
{
uint eth_with_fee = amount.mul(997);
uint numerator = eth_with_fee.mul(reserve1);
uint denominator = reserve0.mul(1000).add(eth_with_fee);
return numerator / denominator;
}
| 16,422,026 |
pragma solidity ^0.4.17;
library SafeMath {
function mul(uint a, uint b) internal pure returns(uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns(uint);
function allowance(address owner, address spender) public view returns(uint);
function transfer(address to, uint value) public returns(bool ok);
function transferFrom(address from, address to, uint value) public returns(bool ok);
function approve(address spender, uint value) public returns(bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
Unpause();
}
}
/// @title Migration Agent interface
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value) public;
}
// Crowdsale Smart Contract
// This smart contract collects ETH and in return sends tokens to the Backers
contract Crowdsale is Pausable {
using SafeMath for uint;
struct Backer {
uint weiReceived; // amount of ETH contributed
uint tokensSent; // amount of tokens sent
bool refunded; // true if user has been refunded
}
Token public token; // Token contract reference
address public multisig; // Multisig contract that will receive the ETH
address public team; // Address to which the team tokens will be sent
address public zen; // Address to which zen team tokens will be sent
uint public ethReceived; // Number of ETH received
uint public totalTokensSent; // Number of tokens sent to ETH contributors
uint public startBlock; // Crowdsale start block
uint public endBlock; // Crowdsale end block
uint public maxCap; // Maximum number of tokens to sell
uint public minCap; // Minimum number of tokens to sell
bool public crowdsaleClosed; // Is crowdsale still in progress
uint public refundCount; // number of refunds
uint public totalRefunded; // total amount of refunds in wei
uint public tokenPriceWei; // tokn price in wei
uint public minInvestETH; // Minimum amount to invest
uint public presaleTokens;
uint public totalWhiteListed;
uint public claimCount;
uint public totalClaimed;
uint public numOfBlocksInMinute; // number of blocks in one minute * 100. eg.
// if one block takes 13.34 seconds, the number will be 60/13.34* 100= 449
mapping(address => Backer) public backers; //backer list
address[] public backersIndex; // to be able to itarate through backers for verification.
mapping(address => bool) public whiteList;
// @notice to verify if action is not performed out of the campaing range
modifier respectTimeFrame() {
require(block.number >= startBlock && block.number <= endBlock);
_;
}
// Events
event LogReceivedETH(address backer, uint amount, uint tokenAmount);
event LogRefundETH(address backer, uint amount);
event LogWhiteListed(address user, uint whiteListedNum);
event LogWhiteListedMultiple(uint whiteListedNum);
// Crowdsale {constructor}
// @notice fired when contract is crated. Initilizes all constant and initial variables.
function Crowdsale() public {
multisig = 0xE804Ad72e60503eD47d267351Bdd3441aC1ccb03;
team = 0x86Ab6dB9932332e3350141c1D2E343C478157d04;
zen = 0x3334f1fBf78e4f0CFE0f5025410326Fe0262ede9;
presaleTokens = 4692000e8; //TODO: ensure that this is correct amount
totalTokensSent = presaleTokens;
minInvestETH = 1 ether/10; // 0.1 eth
startBlock = 0; // ICO start block
endBlock = 0; // ICO end block
maxCap = 42000000e8; // takes into consideration zen team tokens and team tokens.
minCap = 8442000e8;
tokenPriceWei = 80000000000000; // Price is 0.00008 eth
numOfBlocksInMinute = 400; // TODO: updte this value before deploying. E.g. 4.00 block/per minute wold be entered as 400
}
// @notice to populate website with status of the sale
function returnWebsiteData() external view returns(uint, uint, uint, uint, uint, uint, uint, uint, bool, bool) {
return (startBlock, endBlock, numberOfBackers(), ethReceived, maxCap, minCap, totalTokensSent, tokenPriceWei, paused, crowdsaleClosed);
}
// @notice in case refunds are needed, money can be returned to the contract
function fundContract() external payable onlyOwner() returns (bool) {
return true;
}
function addToWhiteList(address _user) external onlyOwner() returns (bool) {
if (whiteList[_user] != true) {
whiteList[_user] = true;
totalWhiteListed++;
LogWhiteListed(_user, totalWhiteListed);
}
return true;
}
function addToWhiteListMultiple(address[] _users) external onlyOwner() returns (bool) {
for (uint i = 0; i < _users.length; ++i) {
if (whiteList[_users[i]] != true) {
whiteList[_users[i]] = true;
totalWhiteListed++;
}
}
LogWhiteListedMultiple(totalWhiteListed);
return true;
}
// @notice Move funds from pre ICO sale if needed.
function transferPreICOFunds() external payable onlyOwner() returns (bool) {
ethReceived = ethReceived.add(msg.value);
return true;
}
// @notice Specify address of token contract
// @param _tokenAddress {address} address of the token contract
// @return res {bool}
function updateTokenAddress(Token _tokenAddress) external onlyOwner() returns(bool res) {
token = _tokenAddress;
return true;
}
// {fallback function}
// @notice It will call internal function which handels allocation of Ether and calculates amout of tokens.
function () external payable {
contribute(msg.sender);
}
// @notice It will be called by owner to start the sale
function start(uint _block) external onlyOwner() {
require(_block < (numOfBlocksInMinute * 60 * 24 * 60)/100); // allow max 60 days for campaign
startBlock = block.number;
endBlock = startBlock.add(_block);
}
// @notice Due to changing average of block time
// this function will allow on adjusting duration of campaign closer to the end
function adjustDuration(uint _block) external onlyOwner() {
require(_block < (numOfBlocksInMinute * 60 * 24 * 80)/100); // allow for max of 80 days for campaign
require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past
endBlock = startBlock.add(_block);
}
// @notice This function will finalize the sale.
// It will only execute if predetermined sale time passed or all tokens are sold.
function finalize() external onlyOwner() {
require(!crowdsaleClosed);
// purchasing precise number of tokens might be impractical,
//thus subtract 1000 tokens so finalizition is possible near the end
require(block.number > endBlock || totalTokensSent >= maxCap - 1000);
require(totalTokensSent >= minCap); // ensure that campaign was successful
crowdsaleClosed = true;
if (!token.transfer(team, 45000000e8 + presaleTokens))
revert();
if (!token.transfer(zen, 3000000e8))
revert();
token.unlock();
}
// @notice
// This function will allow to transfer unsold tokens to a new
// contract/wallet address to start new ICO in the future
function transferRemainingTokens(address _newAddress) external onlyOwner() returns (bool) {
require(_newAddress != address(0));
// 180 days after ICO ends
assert(block.number > endBlock + (numOfBlocksInMinute * 60 * 24 * 180)/100);
if (!token.transfer(_newAddress, token.balanceOf(this)))
revert(); // transfer tokens to admin account or multisig wallet
return true;
}
// @notice Failsafe drain
function drain() external onlyOwner() {
multisig.transfer(this.balance);
}
// @notice it will allow contributors to get refund in case campaign failed
function refund() external whenNotPaused returns (bool) {
require(block.number > endBlock); // ensure that campaign is over
require(totalTokensSent < minCap); // ensure that campaign failed
require(this.balance > 0); // contract will hold 0 ether at the end of the campaign.
// contract needs to be funded through fundContract() for this action
Backer storage backer = backers[msg.sender];
require(backer.weiReceived > 0);
require(!backer.refunded);
backer.refunded = true;
refundCount++;
totalRefunded = totalRefunded + backer.weiReceived;
if (!token.burn(msg.sender, backer.tokensSent))
revert();
msg.sender.transfer(backer.weiReceived);
LogRefundETH(msg.sender, backer.weiReceived);
return true;
}
// @notice return number of contributors
// @return {uint} number of contributors
function numberOfBackers() public view returns(uint) {
return backersIndex.length;
}
// @notice It will be called by fallback function whenever ether is sent to it
// @param _backer {address} address of beneficiary
// @return res {bool} true if transaction was successful
function contribute(address _backer) internal whenNotPaused respectTimeFrame returns(bool res) {
require(msg.value >= minInvestETH); // stop when required minimum is not sent
require(whiteList[_backer]);
uint tokensToSend = calculateNoOfTokensToSend();
require(totalTokensSent.add(tokensToSend) <= maxCap); // Ensure that max cap hasn't been reached
Backer storage backer = backers[_backer];
if (backer.weiReceived == 0)
backersIndex.push(_backer);
backer.tokensSent = backer.tokensSent.add(tokensToSend);
backer.weiReceived = backer.weiReceived.add(msg.value);
ethReceived = ethReceived.add(msg.value); // Update the total Ether recived
totalTokensSent = totalTokensSent.add(tokensToSend);
if (!token.transfer(_backer, tokensToSend))
revert(); // Transfer SOCX tokens
multisig.transfer(msg.value); // send money to multisignature wallet
LogReceivedETH(_backer, msg.value, tokensToSend); // Register event
return true;
}
// @notice This function will return number of tokens based on time intervals in the campaign
function calculateNoOfTokensToSend() internal constant returns (uint) {
uint tokenAmount = msg.value.mul(1e8) / tokenPriceWei;
if (block.number <= startBlock + (numOfBlocksInMinute * 60) / 100) // less then one hour
return tokenAmount + (tokenAmount * 50) / 100;
else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24) / 100) // less than one day
return tokenAmount + (tokenAmount * 25) / 100;
else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 2) / 100) // less than two days
return tokenAmount + (tokenAmount * 10) / 100;
else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 3) / 100) // less than three days
return tokenAmount + (tokenAmount * 5) / 100;
else // after 3 days
return tokenAmount;
}
}
// The SOCX token
contract Token is ERC20, Ownable {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals; // How many decimals to show.
string public version = "v0.1";
uint public initialSupply;
uint public totalSupply;
bool public locked;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address public migrationMaster;
address public migrationAgent;
address public crowdSaleAddress;
uint256 public totalMigrated;
// Lock transfer for contributors during the ICO
modifier onlyUnlocked() {
if (msg.sender != crowdSaleAddress && locked)
revert();
_;
}
modifier onlyAuthorized() {
if (msg.sender != owner && msg.sender != crowdSaleAddress)
revert();
_;
}
// The SOCX Token created with the time at which the crowdsale ends
function Token(address _crowdSaleAddress, address _migrationMaster) public {
// Lock the transfCrowdsaleer function during the crowdsale
locked = true; // Lock the transfer of tokens during the crowdsale
initialSupply = 90000000e8;
totalSupply = initialSupply;
name = "SocialX"; // Set the name for display purposes
symbol = "SOCX"; // Set the symbol for display purposes
decimals = 8; // Amount of decimals for display purposes
crowdSaleAddress = _crowdSaleAddress;
balances[crowdSaleAddress] = totalSupply;
migrationMaster = _migrationMaster;
}
function unlock() public onlyAuthorized {
locked = false;
}
function lock() public onlyAuthorized {
locked = true;
}
event Migrate(address indexed _from, address indexed _to, uint256 _value);
// Token migration support:
/// @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 onlyUnlocked() {
// Abort if not in Operational Migration state.
if (migrationAgent == 0)
revert();
// Validate input value.
if (_value == 0)
revert();
if (_value > balances[msg.sender])
revert();
balances[msg.sender] -= _value;
totalSupply -= _value;
totalMigrated += _value;
MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value);
Migrate(msg.sender, migrationAgent, _value);
}
/// @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 onlyUnlocked() {
// Abort if not in Operational Normal state.
require(migrationAgent == 0);
require(msg.sender == migrationMaster);
migrationAgent = _agent;
}
function resetCrowdSaleAddress(address _newCrowdSaleAddress) external onlyAuthorized() {
crowdSaleAddress = _newCrowdSaleAddress;
}
function setMigrationMaster(address _master) external {
require(msg.sender == migrationMaster);
require(_master != 0);
migrationMaster = _master;
}
// @notice burn tokens in case campaign failed
// @param _member {address} of member
// @param _value {uint} amount of tokens to burn
// @return {bool} true if successful
function burn( address _member, uint256 _value) public onlyAuthorized returns(bool) {
balances[_member] = balances[_member].sub(_value);
totalSupply = totalSupply.sub(_value);
Transfer(_member, 0x0, _value);
return true;
}
// @notice transfer tokens to given address
// @param _to {address} address or recipient
// @param _value {uint} amount to transfer
// @return {bool} true if successful
function transfer(address _to, uint _value) public onlyUnlocked returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
// @notice transfer tokens from given address to another address
// @param _from {address} from whom tokens are transferred
// @param _to {address} to whom tokens are transferred
// @parm _value {uint} amount of tokens to transfer
// @return {bool} true if successful
function transferFrom(address _from, address _to, uint256 _value) public onlyUnlocked returns(bool success) {
require(balances[_from] >= _value); // Check if the sender has enough
require(_value <= allowed[_from][msg.sender]); // Check if allowed is greater or equal
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
// @notice to query balance of account
// @return _owner {address} address of user to query balance
function balanceOf(address _owner) public view returns(uint balance) {
return balances[_owner];
}
/**
* @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, uint _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// @notice to query of allowance of one user to the other
// @param _owner {address} of the owner of the account
// @param _spender {address} of the spender of the account
// @return remaining {uint} amount of remaining allowance
function allowance(address _owner, address _spender) public view returns(uint remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | to populate website with status of the sale | function returnWebsiteData() external view returns(uint, uint, uint, uint, uint, uint, uint, uint, bool, bool) {
return (startBlock, endBlock, numberOfBackers(), ethReceived, maxCap, minCap, totalTokensSent, tokenPriceWei, paused, crowdsaleClosed);
}
| 1,071,674 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.2;
pragma experimental ABIEncoderV2;
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol)
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC1155/extensions/IERC1155MetadataURIUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @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);
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
/**
* @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);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.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() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// OpenZeppelin Contracts v4.4.0 (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 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;
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract 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;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol)
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes 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);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] 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);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (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);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
/* unchecked { */
/* _balances[id][from] = fromBalance - amount; */
/* } */
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
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: burn amount exceeds balance");
/* unchecked { */
/* _balances[id][from] = fromBalance - amount; */
/* } */
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.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 IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.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;
}
uint256[47] private __gap;
}
// File: contracts/ICounterfactualNFT.sol
// Copyright 2017 Loopring Technology Limited.
/**
* @title ICounterfactualNFT
*/
abstract contract ICounterfactualNFT
{
function initialize(address owner, string memory _uri)
public
virtual;
}
// File: contracts/AddressSet.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AddressSet
/// @author Daniel Wang - <[email protected]>
contract AddressSet
{
struct Set
{
address[] addresses;
mapping (address => uint) positions;
uint count;
}
mapping (bytes32 => Set) private sets;
function addAddressToSet(
bytes32 key,
address addr,
bool maintainList
) internal
{
Set storage set = sets[key];
require(set.positions[addr] == 0, "ALREADY_IN_SET");
if (maintainList) {
require(set.addresses.length == set.count, "PREVIOUSLY_NOT_MAINTAINED");
set.addresses.push(addr);
} else {
require(set.addresses.length == 0, "MUST_MAINTAIN");
}
set.count += 1;
set.positions[addr] = set.count;
}
function removeAddressFromSet(
bytes32 key,
address addr
)
internal
{
Set storage set = sets[key];
uint pos = set.positions[addr];
require(pos != 0, "NOT_IN_SET");
delete set.positions[addr];
set.count -= 1;
if (set.addresses.length > 0) {
address lastAddr = set.addresses[set.count];
if (lastAddr != addr) {
set.addresses[pos - 1] = lastAddr;
set.positions[lastAddr] = pos;
}
set.addresses.pop();
}
}
function removeSet(bytes32 key)
internal
{
delete sets[key];
}
function isAddressInSet(
bytes32 key,
address addr
)
internal
view
returns (bool)
{
return sets[key].positions[addr] != 0;
}
function numAddressesInSet(bytes32 key)
internal
view
returns (uint)
{
Set storage set = sets[key];
return set.count;
}
function addressesInSet(bytes32 key)
internal
view
returns (address[] memory)
{
Set storage set = sets[key];
require(set.count == set.addresses.length, "NOT_MAINTAINED");
return sets[key].addresses;
}
}
// File: contracts/external/IL2MintableNFT.sol
// Copyright 2017 Loopring Technology Limited.
interface IL2MintableNFT
{
/// @dev This function is called when an NFT minted on L2 is withdrawn from Loopring.
/// That means the NFTs were burned on L2 and now need to be minted on L1.
///
/// This function can only be called by the Loopring exchange.
///
/// @param to The owner of the NFT
/// @param tokenId The token type 'id`
/// @param amount The amount of NFTs to mint
/// @param minter The minter on L2, which can be used to decide if the NFT is authentic
/// @param data Opaque data that can be used by the contract
function mintFromL2(
address to,
uint256 tokenId,
uint amount,
address minter,
bytes calldata data
)
external;
/// @dev Returns a list of all address that are authorized to mint NFTs on L2.
/// @return The list of authorized minter on L2
function minters()
external
view
returns (address[] memory);
}
// File: contracts/external/IPFS.sol
/// @title IPFS
/// @author Brecht Devos - <[email protected]>
library IPFS
{
bytes constant ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
// Encodes the 32 byte data as an IPFS v0 CID
function encode(uint256 data)
internal
pure
returns (string memory)
{
// We'll be always be encoding 34 bytes
bytes memory out = new bytes(46);
// Copy alphabet to memory
bytes memory alphabet = ALPHABET;
// We have to encode 0x1220data, which is 34 bytes and doesn't fit in a single uint256.
// Keep the first 32 bytes in the uint, but do the encoding as if 0x1220 was part of the data value.
// 0 = (0x12200000000000000000000000000000000000000000000000000000000000000000) % 58
out[45] = alphabet[data % 58];
data /= 58;
// 4 = (0x12200000000000000000000000000000000000000000000000000000000000000000 / 58) % 58
data += 4;
out[44] = alphabet[data % 58];
data /= 58;
// 40 = (0x12200000000000000000000000000000000000000000000000000000000000000000 / 58 / 58) % 58
data += 40;
out[43] = alphabet[data % 58];
data /= 58;
// Add the top bytes now there is anough space in the uint256
// This constant is 0x12200000000000000000000000000000000000000000000000000000000000000000 / 58 / 58 / 58
data += 2753676319555676466672318311740497214108679778017611511045364661305900823779;
// The rest is just simple base58 encoding
for (uint i = 3; i < 46; i++) {
out[45 - i] = alphabet[data % 58];
data /= 58;
}
return string(out);
}
}
// File: contracts/external/OwnableUpgradeable.sol
// Copied from Open-Zeppelin, changed `_owner` to public for gas optimizations.
/**
* @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 public _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 {
_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);
}
uint256[49] private __gap;
}
// File: ../contracts/CounterfactualNFT.sol
// Copyright 2017 Loopring Technology Limited.
/**
* @title CounterfactualNFT
*/
contract CounterfactualNFT is ICounterfactualNFT, Initializable, ERC1155Upgradeable, OwnableUpgradeable, IL2MintableNFT, AddressSet
{
event MintFromL2(
address owner,
uint256 id,
uint amount,
address minter
);
bytes32 internal constant MINTERS = keccak256("__MINTERS__");
bytes32 internal constant DEPRECATED_MINTERS = keccak256("__DEPRECATED_MINTERS__");
address public immutable layer2Address;
modifier onlyFromLayer2
{
require(msg.sender == layer2Address, "not authorized");
_;
}
modifier onlyFromMinter
{
require(isMinter(msg.sender), "not authorized");
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(address _layer2Address)
initializer
{
layer2Address = _layer2Address;
// Disable implementation contract
_owner = 0x000000000000000000000000000000000000dEaD;
}
function initialize(address owner, string memory _uri)
public
override
{
require(_owner == address(0), "ALREADY_INITIALIZED");
_owner = owner;
if (bytes(_uri).length != 0) {
_setURI(_uri);
}
}
function setURI(string memory _uri)
public
onlyOwner
{
_setURI(_uri);
}
function mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
)
external
onlyFromMinter
{
_mint(account, id, amount, data);
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
external
onlyFromMinter
{
_mintBatch(to, ids, amounts, data);
}
function setMinter(
address minter,
bool enabled
)
external
onlyOwner
{
if (enabled) {
addAddressToSet(MINTERS, minter, true);
if (isAddressInSet(DEPRECATED_MINTERS, minter)) {
removeAddressFromSet(DEPRECATED_MINTERS, minter);
}
} else {
removeAddressFromSet(MINTERS, minter);
if (!isAddressInSet(DEPRECATED_MINTERS, minter)) {
addAddressToSet(DEPRECATED_MINTERS, minter, true);
}
}
}
function transferOwnership(address newOwner)
public
virtual
override
onlyOwner
{
require(newOwner != owner(), "INVALID_OWNER");
// Make sure NFTs minted by the previous owner remain valid
if (!isAddressInSet(DEPRECATED_MINTERS, owner())) {
addAddressToSet(DEPRECATED_MINTERS, owner(), true);
}
// Now transfer the ownership like usual
super.transferOwnership(newOwner);
}
function uri(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
string memory baseURI = super.uri(tokenId);
if (bytes(baseURI).length == 0) {
// If no base URI is set we interpret the tokenId as an IPFS hash
return string(
abi.encodePacked(
"ipfs://",
IPFS.encode(tokenId),
"/metadata.json"
)
);
} else {
return baseURI;
}
}
// Layer 2 logic
function mintFromL2(
address to,
uint256 id,
uint amount,
address minter,
bytes calldata data
)
external
override
onlyFromLayer2
{
require(isMinter(minter) || isAddressInSet(DEPRECATED_MINTERS, minter), "invalid minter");
_mint(to, id, amount, data);
emit MintFromL2(to, id, amount, minter);
}
function minters()
public
view
override
returns (address[] memory)
{
address[] memory minterAddresses = addressesInSet(MINTERS);
address[] memory deprecatedAddresses = addressesInSet(DEPRECATED_MINTERS);
address[] memory mintersAndOwner = new address[](minterAddresses.length + deprecatedAddresses.length + 1);
uint idx = 0;
for (uint i = 0; i < minterAddresses.length; i++) {
mintersAndOwner[idx++] = minterAddresses[i];
}
for (uint i = 0; i < deprecatedAddresses.length; i++) {
mintersAndOwner[idx++] = deprecatedAddresses[i];
}
// Owner could already be added to the minters, but that's fine
mintersAndOwner[idx++] = owner();
return mintersAndOwner;
}
function isMinter(address addr)
public
view
returns (bool)
{
// Also allow the owner to mint NFTs to save on gas (no additional minter needs to be set)
return addr == owner() || isAddressInSet(MINTERS, addr);
}
} | Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165Upgradeable {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
pragma solidity ^0.8.2;
}
| 14,585,941 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
contract Lands {
struct Land {
address municipal;
uint256 id;
uint256 from;
uint256 to;
uint256 ammount;
}
mapping(uint256 => Land) public lands;
// mapping(address => Land) public landsByAddress;
uint256 public landsCounter;
mapping(address => uint256) public CounterByAddress;
mapping (address => mapping (uint => Land)) public landsByAddress;
constructor() public {
landsCounter = 0;
}
function registerLand(
address _municipal,
uint256 _id,
uint256 _from,
uint256 _to,
uint256 _ammount
) public {
landsCounter++;
CounterByAddress[_municipal]++;
lands[landsCounter] = Land(_municipal, _id, _from, _to, _ammount);
landsByAddress[_municipal][CounterByAddress[_municipal]] = Land(
_municipal,
_id,
_from,
_to,
_ammount
);
// landsByAddress[_municipal][landsCounter] = Land(_municipal, _id, _from, _to, _ammount);
}
function getContractByAddress(address _municipal)
public
view
returns (
address,
uint256,
uint256,
uint256,
uint256
)
{
for (uint256 i = 1; i < landsCounter; i++) {
if (landsByAddress[_municipal][i].municipal == _municipal) {
return (
landsByAddress[_municipal][i].municipal,
landsByAddress[_municipal][i].id,
landsByAddress[_municipal][i].from,
landsByAddress[_municipal][i].to,
landsByAddress[_municipal][i].ammount
);
}
}
}
}
| landsByAddress[_municipal][landsCounter] = Land(_municipal, _id, _from, _to, _ammount); | function registerLand(
address _municipal,
uint256 _id,
uint256 _from,
uint256 _to,
uint256 _ammount
) public {
landsCounter++;
CounterByAddress[_municipal]++;
lands[landsCounter] = Land(_municipal, _id, _from, _to, _ammount);
landsByAddress[_municipal][CounterByAddress[_municipal]] = Land(
_municipal,
_id,
_from,
_to,
_ammount
);
}
| 12,828,005 |
./full_match/43114/0xC4729E56b831d74bBc18797e0e17A295fA77488c/sources/contracts/YakRouter.sol | Query single adapter/ | function queryAdapter(
uint256 _amountIn,
address _tokenIn,
address _tokenOut,
uint8 _index
) external view returns (uint256) {
IAdapter _adapter = IAdapter(ADAPTERS[_index]);
uint amountOut = _adapter.query(_amountIn, _tokenIn, _tokenOut);
return amountOut;
}
| 4,551,348 |
./partial_match/1/0x4C71F0B8296515f1e87b8572DEee2A41116D1Da0/sources/Miles.sol | exclude from paying fees or having max transaction amount | constructor() ERC20(unicode"Miles Inu", unicode"MILES") {
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 = 5;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1000000000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0xAc1F33Cb16a828F17a22b868dc37F7c62f7A38ac);
devWallet = address(0xAc1F33Cb16a828F17a22b868dc37F7c62f7A38ac);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(address(marketingWallet), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(address(devWallet), true);
excludeFromMaxTransaction(address(marketingWallet), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,951,892 |
pragma solidity 0.4.24;
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @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
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != 0);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
/**
* @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));
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));
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];
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
minters.add(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
minters.add(account);
emit MinterAdded(account);
}
function renounceMinter() public {
minters.remove(msg.sender);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
event MintingFinished();
bool private _mintingFinished = false;
modifier onlyBeforeMintingFinished() {
require(!_mintingFinished);
_;
}
/**
* @return true if the minting is finished.
*/
function mintingFinished() public view returns(bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 amount
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mint(to, amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting()
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mintingFinished = true;
emit MintingFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
/**
* @dev Overrides ERC20._burn in order for burn and burnFrom to emit
* an additional Burn event.
*/
function _burn(address who, uint256 value) internal {
super._burn(who, value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
}
// File: contracts/robonomics/XRT.sol
contract XRT is ERC20Mintable, ERC20Burnable, ERC20Detailed {
constructor() public ERC20Detailed("XRT", "Robonomics Beta", 9) {
uint256 INITIAL_SUPPLY = 1000 * (10 ** 9);
_mint(msg.sender, INITIAL_SUPPLY);
}
}
// File: contracts/robonomics/RobotLiabilityAPI.sol
//import './LiabilityFactory.sol';
contract RobotLiabilityAPI {
bytes public model;
bytes public objective;
bytes public result;
ERC20 public token;
uint256 public cost;
uint256 public lighthouseFee;
uint256 public validatorFee;
bytes32 public demandHash;
bytes32 public offerHash;
address public promisor;
address public promisee;
address public validator;
bool public isSuccess;
bool public isFinalized;
LiabilityFactory public factory;
event Finalized(bool indexed success, bytes result);
}
// File: contracts/robonomics/LightContract.sol
contract LightContract {
/**
* @dev Shared code smart contract
*/
address lib;
constructor(address _library) public {
lib = _library;
}
function() public {
require(lib.delegatecall(msg.data));
}
}
// File: contracts/robonomics/RobotLiability.sol
// Standard robot liability light contract
contract RobotLiability is RobotLiabilityAPI, LightContract {
constructor(address _lib) public LightContract(_lib)
{ factory = LiabilityFactory(msg.sender); }
}
// File: contracts/robonomics/SingletonHash.sol
contract SingletonHash {
event HashConsumed(bytes32 indexed hash);
/**
* @dev Used hash accounting
*/
mapping(bytes32 => bool) public isHashConsumed;
/**
* @dev Parameter can be used only once
* @param _hash Single usage hash
*/
function singletonHash(bytes32 _hash) internal {
require(!isHashConsumed[_hash]);
isHashConsumed[_hash] = true;
emit HashConsumed(_hash);
}
}
// File: contracts/robonomics/DutchAuction.sol
/// @title Dutch auction contract - distribution of XRT tokens using an auction.
/// @author Stefan George - <[email protected]>
/// @author Airalab - <[email protected]>
contract DutchAuction {
/*
* Events
*/
event BidSubmission(address indexed sender, uint256 amount);
/*
* Constants
*/
uint constant public MAX_TOKENS_SOLD = 800 * 10**9; // 8M XRT = 10M - 1M (Foundation) - 1M (Early investors base)
uint constant public WAITING_PERIOD = 0; // 1 days;
/*
* Storage
*/
XRT public xrt;
address public ambix;
address public wallet;
address public owner;
uint public ceiling;
uint public priceFactor;
uint public startBlock;
uint public endTime;
uint public totalReceived;
uint public finalPrice;
mapping (address => uint) public bids;
Stages public stage;
/*
* Enums
*/
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TradingStarted
}
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
// Contract on stage
require(stage == _stage);
_;
}
modifier isOwner() {
// Only owner is allowed to proceed
require(msg.sender == owner);
_;
}
modifier isWallet() {
// Only wallet is allowed to proceed
require(msg.sender == wallet);
_;
}
modifier isValidPayload() {
require(msg.data.length == 4 || msg.data.length == 36);
_;
}
modifier timedTransitions() {
if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice())
finalizeAuction();
if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD)
stage = Stages.TradingStarted;
_;
}
/*
* Public functions
*/
/// @dev Contract constructor function sets owner.
/// @param _wallet Multisig wallet.
/// @param _ceiling Auction ceiling.
/// @param _priceFactor Auction price factor.
constructor(address _wallet, uint _ceiling, uint _priceFactor)
public
{
require(_wallet != 0 && _ceiling > 0 && _priceFactor > 0);
owner = msg.sender;
wallet = _wallet;
ceiling = _ceiling;
priceFactor = _priceFactor;
stage = Stages.AuctionDeployed;
}
/// @dev Setup function sets external contracts' addresses.
/// @param _xrt Robonomics token address.
/// @param _ambix Distillation cube address.
function setup(address _xrt, address _ambix)
public
isOwner
atStage(Stages.AuctionDeployed)
{
// Validate argument
require(_xrt != 0 && _ambix != 0);
xrt = XRT(_xrt);
ambix = _ambix;
// Validate token balance
require(xrt.balanceOf(this) == MAX_TOKENS_SOLD);
stage = Stages.AuctionSetUp;
}
/// @dev Starts auction and sets startBlock.
function startAuction()
public
isWallet
atStage(Stages.AuctionSetUp)
{
stage = Stages.AuctionStarted;
startBlock = block.number;
}
/// @dev Calculates current token price.
/// @return Returns token price.
function calcCurrentTokenPrice()
public
timedTransitions
returns (uint)
{
if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted)
return finalPrice;
return calcTokenPrice();
}
/// @dev Returns correct stage, even if a function with timedTransitions modifier has not yet been called yet.
/// @return Returns current auction stage.
function updateStage()
public
timedTransitions
returns (Stages)
{
return stage;
}
/// @dev Allows to send a bid to the auction.
/// @param receiver Bid will be assigned to this address if set.
function bid(address receiver)
public
payable
isValidPayload
timedTransitions
atStage(Stages.AuctionStarted)
returns (uint amount)
{
require(msg.value > 0);
amount = msg.value;
// If a bid is done on behalf of a user via ShapeShift, the receiver address is set.
if (receiver == 0)
receiver = msg.sender;
// Prevent that more than 90% of tokens are sold. Only relevant if cap not reached.
uint maxWei = MAX_TOKENS_SOLD * calcTokenPrice() / 10**9 - totalReceived;
uint maxWeiBasedOnTotalReceived = ceiling - totalReceived;
if (maxWeiBasedOnTotalReceived < maxWei)
maxWei = maxWeiBasedOnTotalReceived;
// Only invest maximum possible amount.
if (amount > maxWei) {
amount = maxWei;
// Send change back to receiver address. In case of a ShapeShift bid the user receives the change back directly.
receiver.transfer(msg.value - amount);
}
// Forward funding to ether wallet
wallet.transfer(amount);
bids[receiver] += amount;
totalReceived += amount;
emit BidSubmission(receiver, amount);
// Finalize auction when maxWei reached
if (amount == maxWei)
finalizeAuction();
}
/// @dev Claims tokens for bidder after auction.
/// @param receiver Tokens will be assigned to this address if set.
function claimTokens(address receiver)
public
isValidPayload
timedTransitions
atStage(Stages.TradingStarted)
{
if (receiver == 0)
receiver = msg.sender;
uint tokenCount = bids[receiver] * 10**9 / finalPrice;
bids[receiver] = 0;
require(xrt.transfer(receiver, tokenCount));
}
/// @dev Calculates stop price.
/// @return Returns stop price.
function calcStopPrice()
view
public
returns (uint)
{
return totalReceived * 10**9 / MAX_TOKENS_SOLD + 1;
}
/// @dev Calculates token price.
/// @return Returns token price.
function calcTokenPrice()
view
public
returns (uint)
{
return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1;
}
/*
* Private functions
*/
function finalizeAuction()
private
{
stage = Stages.AuctionEnded;
finalPrice = totalReceived == ceiling ? calcTokenPrice() : calcStopPrice();
uint soldTokens = totalReceived * 10**9 / finalPrice;
if (totalReceived == ceiling) {
// Auction contract transfers all unsold tokens to Ambix contract
require(xrt.transfer(ambix, MAX_TOKENS_SOLD - soldTokens));
} else {
// Auction contract burn all unsold tokens
xrt.burn(MAX_TOKENS_SOLD - soldTokens);
}
endTime = now;
}
}
// File: contracts/robonomics/LighthouseAPI.sol
//import './LiabilityFactory.sol';
contract LighthouseAPI {
address[] public members;
function membersLength() public view returns (uint256)
{ return members.length; }
mapping(address => uint256) indexOf;
mapping(address => uint256) public balances;
uint256 public minimalFreeze;
uint256 public timeoutBlocks;
LiabilityFactory public factory;
XRT public xrt;
uint256 public keepaliveBlock = 0;
uint256 public marker = 0;
uint256 public quota = 0;
function quotaOf(address _member) public view returns (uint256)
{ return balances[_member] / minimalFreeze; }
}
// File: contracts/robonomics/Lighthouse.sol
contract Lighthouse is LighthouseAPI, LightContract {
constructor(
address _lib,
uint256 _minimalFreeze,
uint256 _timeoutBlocks
)
public
LightContract(_lib)
{
require(_minimalFreeze > 0 && _timeoutBlocks > 0);
minimalFreeze = _minimalFreeze;
timeoutBlocks = _timeoutBlocks;
factory = LiabilityFactory(msg.sender);
xrt = factory.xrt();
}
}
// File: ens/contracts/AbstractENS.sol
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function ttl(bytes32 node) constant returns(uint64);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
function setTTL(bytes32 node, uint64 ttl);
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
}
// File: ens/contracts/ENS.sol
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if(records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode sha3(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) {
var subnode = sha3(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// File: ens/contracts/PublicResolver.sol
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
AbstractENS ens;
mapping(bytes32=>address) addresses;
mapping(bytes32=>bytes32) hashes;
modifier only_owner(bytes32 node) {
if(ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) {
ens = ensAddr;
}
/**
* Fallback function.
*/
function() {
throw;
}
/**
* Returns true if the specified node has the specified record type.
* @param node The ENS node to query.
* @param kind The record type name, as specified in EIP137.
* @return True if this resolver has a record of the provided type on the
* provided node.
*/
function has(bytes32 node, bytes32 kind) constant returns (bool) {
return (kind == "addr" && addresses[node] != 0) || (kind == "hash" && hashes[node] != 0);
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) constant returns (bool) {
return interfaceID == 0x3b3b57de || interfaceID == 0xd8389dc5;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) constant returns (address ret) {
ret = addresses[node];
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) {
addresses[node] = addr;
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) constant returns (bytes32 ret) {
ret = hashes[node];
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) {
hashes[node] = hash;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
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
{
require(token.approve(spender, value));
}
}
// File: contracts/robonomics/LiabilityFactory.sol
contract LiabilityFactory is SingletonHash {
constructor(
address _robot_liability_lib,
address _lighthouse_lib,
DutchAuction _auction,
XRT _xrt,
ENS _ens
) public {
robotLiabilityLib = _robot_liability_lib;
lighthouseLib = _lighthouse_lib;
auction = _auction;
xrt = _xrt;
ens = _ens;
}
using SafeERC20 for XRT;
using SafeERC20 for ERC20;
/**
* @dev New liability created
*/
event NewLiability(address indexed liability);
/**
* @dev New lighthouse created
*/
event NewLighthouse(address indexed lighthouse, string name);
/**
* @dev Robonomics dutch auction contract
*/
DutchAuction public auction;
/**
* @dev Robonomics network protocol token
*/
XRT public xrt;
/**
* @dev Ethereum name system
*/
ENS public ens;
/**
* @dev Total GAS utilized by Robonomics network
*/
uint256 public totalGasUtilizing = 0;
/**
* @dev GAS utilized by liability contracts
*/
mapping(address => uint256) public gasUtilizing;
/**
* @dev The count of utilized gas for switch to next epoch
*/
uint256 public constant gasEpoch = 347 * 10**10;
/**
* @dev Weighted average gasprice
*/
uint256 public constant gasPrice = 10 * 10**9;
/**
* @dev Lighthouse accounting
*/
mapping(address => bool) public isLighthouse;
/**
* @dev Robot liability shared code smart contract
*/
address public robotLiabilityLib;
/**
* @dev Lightouse shared code smart contract
*/
address public lighthouseLib;
/**
* @dev XRT emission value for utilized gas
*/
function wnFromGas(uint256 _gas) public view returns (uint256) {
// Just return wn=gas when auction isn't finish
if (auction.finalPrice() == 0)
return _gas;
// Current gas utilization epoch
uint256 epoch = totalGasUtilizing / gasEpoch;
// XRT emission with addition coefficient by gas utilzation epoch
uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice();
// Check to not permit emission decrease below wn=gas
return wn < _gas ? _gas : wn;
}
/**
* @dev Only lighthouse guard
*/
modifier onlyLighthouse {
require(isLighthouse[msg.sender]);
_;
}
/**
* @dev Create robot liability smart contract
* @param _demand ABI-encoded demand message
* @param _offer ABI-encoded offer message
*/
function createLiability(
bytes _demand,
bytes _offer
)
external
onlyLighthouse
returns (RobotLiability liability)
{
// Store in memory available gas
uint256 gasinit = gasleft();
// Create liability
liability = new RobotLiability(robotLiabilityLib);
emit NewLiability(liability);
// Parse messages
require(liability.call(abi.encodePacked(bytes4(0x0be8947a), _demand))); // liability.demand(...)
singletonHash(liability.demandHash());
require(liability.call(abi.encodePacked(bytes4(0x87bca1cf), _offer))); // liability.offer(...)
singletonHash(liability.offerHash());
// Transfer lighthouse fee to lighthouse worker directly
if (liability.lighthouseFee() > 0)
xrt.safeTransferFrom(liability.promisor(),
tx.origin,
liability.lighthouseFee());
// Transfer liability security and hold on contract
ERC20 token = liability.token();
if (liability.cost() > 0)
token.safeTransferFrom(liability.promisee(),
liability,
liability.cost());
// Transfer validator fee and hold on contract
if (address(liability.validator()) != 0 && liability.validatorFee() > 0)
xrt.safeTransferFrom(liability.promisee(),
liability,
liability.validatorFee());
// Accounting gas usage of transaction
uint256 gas = gasinit - gasleft() + 110525; // Including observation error
totalGasUtilizing += gas;
gasUtilizing[liability] += gas;
}
/**
* @dev Create lighthouse smart contract
* @param _minimalFreeze Minimal freeze value of XRT token
* @param _timeoutBlocks Max time of lighthouse silence in blocks
* @param _name Lighthouse subdomain,
* example: for 'my-name' will created 'my-name.lighthouse.1.robonomics.eth' domain
*/
function createLighthouse(
uint256 _minimalFreeze,
uint256 _timeoutBlocks,
string _name
)
external
returns (address lighthouse)
{
bytes32 lighthouseNode
// lighthouse.2.robonomics.eth
= 0xa058d6058d5ec525aa555c572720908a8d6ea6e2781b460bdecb2abf8bf56d4c;
// Name reservation check
bytes32 subnode = keccak256(abi.encodePacked(lighthouseNode, keccak256(_name)));
require(ens.resolver(subnode) == 0);
// Create lighthouse
lighthouse = new Lighthouse(lighthouseLib, _minimalFreeze, _timeoutBlocks);
emit NewLighthouse(lighthouse, _name);
isLighthouse[lighthouse] = true;
// Register subnode
ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this);
// Register lighthouse address
PublicResolver resolver = PublicResolver(ens.resolver(lighthouseNode));
ens.setResolver(subnode, resolver);
resolver.setAddr(subnode, lighthouse);
}
/**
* @dev Is called whan after liability finalization
* @param _gas Liability finalization gas expenses
*/
function liabilityFinalized(
uint256 _gas
)
external
returns (bool)
{
require(gasUtilizing[msg.sender] > 0);
uint256 gas = _gas - gasleft();
require(_gas > gas);
totalGasUtilizing += gas;
gasUtilizing[msg.sender] += gas;
require(xrt.mint(tx.origin, wnFromGas(gasUtilizing[msg.sender])));
return true;
}
} | Returns the content hash associated with an ENS node. Note that this resource type is not standardized, and will likely change in future to a resource type based on multihash. node The ENS node to query. return The associated content hash./ | function content(bytes32 node) constant returns (bytes32 ret) {
ret = hashes[node];
}
| 1,126,873 |
./full_match/137/0x920B71acd270420A0d98cD54Af5a1299f3A59dc0/sources/contracts/RTGasStation.sol | Function to allow owner to change beneficiary of fees | function setFeeBeneficiary(address beneficiary) public onlyOwner {
REWARD_TOOLS_BENEFICIARY = beneficiary;
}
| 4,672,720 |
./partial_match/1/0xC5617E515B47561AD1F394b6B08Bc71f7EdA1D7c/sources/PepeBackCoin.sol | Destroys `amount` tokens from `account`, reducing the - `account` cannot be the zero address. - `account` must have at least `amount` tokens. total supply./ Overflow not possible: amount <= accountBalance <= totalSupply. | 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);
}
| 4,258,832 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
contract MyTest is ERC721Enumerable, Ownable, ERC721Burnable, ERC721Pausable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
uint256 public MAX_ELEMENTS = 1200;
uint256 public constant PRICE = 1 * 10**17; // 0.1 ETH
uint256 public constant MAX_BY_MINT = 10;
uint256 public constant MAX_PER_ADDRESS = 10;
uint256 public SOLD_OUT_ELEMENTS = 449;
uint256 public constant reveal_timestamp = 1634954400000; // Sat Oct 22nd 2021 10 PM EST
address public devAddress; // account
string public baseTokenURI; // IPFS
event CreateMyTest(uint256 indexed id);
constructor(string memory baseURI, address DEV_ADDRESS) ERC721("My Test", "MTTT") {
devAddress = DEV_ADDRESS;
setBaseURI(baseURI);
pause(true);
}
modifier saleIsOpen {
require(_totalSupply() <= (MAX_ELEMENTS - SOLD_OUT_ELEMENTS), "Sale end");
if (_msgSender() != owner()) {
require(!paused(), "Pausable: paused");
}
_;
}
modifier saleIsReveal {
require(block.timestamp >= reveal_timestamp, "Not revealed yet");
_;
}
function _totalSupply() internal view returns (uint) {
return _tokenIdTracker.current();
}
function totalMint() public view returns (uint256) {
return _totalSupply();
}
// multiple mint (saleIsReveal)
function mint(address _to, uint256 _count) public payable saleIsOpen {
uint256 total = _totalSupply();
require(total + _count <= (MAX_ELEMENTS - SOLD_OUT_ELEMENTS), "Mint: over Max limit");
require(_count <= MAX_BY_MINT, "Exceeds number");
require(balanceOf(_to) + _count <= MAX_PER_ADDRESS, "Exceeds balance");
require(msg.value >= price(_count), "Value below price");
for (uint256 i = 0; i < _count; i++) {
_mintAnElement(_to);
}
}
// this is for presale
function presaleMint(address _to, uint256 id) public payable onlyOwner {
require(ownerOf(id) == address(0), "Already minted");
_tokenIdTracker.increment();
_safeMint(_to, id);
emit CreateMyTest(id);
}
// mint one Token to sender
function _mintAnElement(address _to) private {
uint id = _totalSupply();
_tokenIdTracker.increment();
_safeMint(_to, id);
emit CreateMyTest(id);
}
// the total price of token amounts which the sender will mint
function price(uint256 _count) public pure returns (uint256) {
return PRICE.mul(_count);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
// set BaseURI
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
// set MAX_ELEMENTS
function setMaxElements(uint256 _count) public onlyOwner {
MAX_ELEMENTS = _count;
}
// set MAX_ELEMENTS
function setSoldOutElements(uint256 _count) public onlyOwner {
SOLD_OUT_ELEMENTS = _count;
}
// get wallet infos
function walletOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
// set the state of market
function pause(bool val) public onlyOwner {
if (val == true) {
_pause();
return;
}
_unpause();
}
// withdraw all coins
function withdrawAll() public payable onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0);
_widthdraw(devAddress, balance);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
// override function
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
// set dev address
function setDevAddr(address new_dev_addr) public onlyOwner{
require(new_dev_addr != address(0), 'Invalid address');
devAddress = new_dev_addr;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../security/Pausable.sol";
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | mint one Token to sender | function _mintAnElement(address _to) private {
uint id = _totalSupply();
_tokenIdTracker.increment();
_safeMint(_to, id);
emit CreateMyTest(id);
}
| 14,383,202 |
./full_match/1/0x43844369A7a6e83b6DA64B9b3121B4b66d71Cad0/sources/contracts/party/PartyGovernance.sol | Setup the arguments for the proposal execution engine. Execute the proposal. | function _executeProposal(
uint256 proposalId,
Proposal memory proposal,
IERC721[] memory preciousTokens,
uint256[] memory preciousTokenIds,
uint256 flags,
bytes memory progressData,
bytes memory extraData
) private returns (bool completed) {
IProposalExecutionEngine.ExecuteProposalParams
memory executeParams = IProposalExecutionEngine.ExecuteProposalParams({
proposalId: proposalId,
proposalData: proposal.proposalData,
progressData: progressData,
extraData: extraData,
preciousTokens: preciousTokens,
preciousTokenIds: preciousTokenIds,
flags: flags
});
{
(bool success, bytes memory resultData) = address(_getProposalExecutionEngine())
.delegatecall(
abi.encodeCall(IProposalExecutionEngine.executeProposal, (executeParams))
);
if (!success) {
resultData.rawRevert();
}
nextProgressData = abi.decode(resultData, (bytes));
}
emit ProposalExecuted(proposalId, msg.sender, nextProgressData);
}
| 17,141,435 |
pragma solidity 0.4.18;
contract Utils {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 1B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH
uint constant internal MAX_DECIMALS = 18;
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
interface ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
function PermissionGroups() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[]) {
return operatorsGroup;
}
function getAlerters () external view returns(address[]) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]); // prevent duplicates.
AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
OperatorAdded(operator, false);
break;
}
}
}
}
contract Withdrawable is PermissionGroups {
event TokenWithdraw(ERC20 token, uint amount, address sendTo);
/**
* @dev Withdraw all ERC20 compatible tokens
* @param token ERC20 The address of the token contract
*/
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
TokenWithdraw(token, amount, sendTo);
}
event EtherWithdraw(uint amount, address sendTo);
/**
* @dev Withdraw Ethers
*/
function withdrawEther(uint amount, address sendTo) external onlyAdmin {
sendTo.transfer(amount);
EtherWithdraw(amount, sendTo);
}
}
contract VolumeImbalanceRecorder is Withdrawable {
uint constant internal SLIDING_WINDOW_SIZE = 5;
uint constant internal POW_2_64 = 2 ** 64;
struct TokenControlInfo {
uint minimalRecordResolution; // can be roughly 1 cent
uint maxPerBlockImbalance; // in twei resolution
uint maxTotalImbalance; // max total imbalance (between rate updates)
// before halting trade
}
mapping(address => TokenControlInfo) internal tokenControlInfo;
struct TokenImbalanceData {
int lastBlockBuyUnitsImbalance;
uint lastBlock;
int totalBuyUnitsImbalance;
uint lastRateUpdateBlock;
}
mapping(address => mapping(uint=>uint)) public tokenImbalanceData;
function VolumeImbalanceRecorder(address _admin) public {
require(_admin != address(0));
admin = _admin;
}
function setTokenControlInfo(
ERC20 token,
uint minimalRecordResolution,
uint maxPerBlockImbalance,
uint maxTotalImbalance
)
public
onlyAdmin
{
tokenControlInfo[token] =
TokenControlInfo(
minimalRecordResolution,
maxPerBlockImbalance,
maxTotalImbalance
);
}
function getTokenControlInfo(ERC20 token) public view returns(uint, uint, uint) {
return (tokenControlInfo[token].minimalRecordResolution,
tokenControlInfo[token].maxPerBlockImbalance,
tokenControlInfo[token].maxTotalImbalance);
}
function addImbalance(
ERC20 token,
int buyAmount,
uint rateUpdateBlock,
uint currentBlock
)
internal
{
uint currentBlockIndex = currentBlock % SLIDING_WINDOW_SIZE;
int recordedBuyAmount = int(buyAmount / int(tokenControlInfo[token].minimalRecordResolution));
int prevImbalance = 0;
TokenImbalanceData memory currentBlockData =
decodeTokenImbalanceData(tokenImbalanceData[token][currentBlockIndex]);
// first scenario - this is not the first tx in the current block
if (currentBlockData.lastBlock == currentBlock) {
if (uint(currentBlockData.lastRateUpdateBlock) == rateUpdateBlock) {
// just increase imbalance
currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount;
currentBlockData.totalBuyUnitsImbalance += recordedBuyAmount;
} else {
// imbalance was changed in the middle of the block
prevImbalance = getImbalanceInRange(token, rateUpdateBlock, currentBlock);
currentBlockData.totalBuyUnitsImbalance = int(prevImbalance) + recordedBuyAmount;
currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount;
currentBlockData.lastRateUpdateBlock = uint(rateUpdateBlock);
}
} else {
// first tx in the current block
int currentBlockImbalance;
(prevImbalance, currentBlockImbalance) = getImbalanceSinceRateUpdate(token, rateUpdateBlock, currentBlock);
currentBlockData.lastBlockBuyUnitsImbalance = recordedBuyAmount;
currentBlockData.lastBlock = uint(currentBlock);
currentBlockData.lastRateUpdateBlock = uint(rateUpdateBlock);
currentBlockData.totalBuyUnitsImbalance = int(prevImbalance) + recordedBuyAmount;
}
tokenImbalanceData[token][currentBlockIndex] = encodeTokenImbalanceData(currentBlockData);
}
function setGarbageToVolumeRecorder(ERC20 token) internal {
for (uint i = 0; i < SLIDING_WINDOW_SIZE; i++) {
tokenImbalanceData[token][i] = 0x1;
}
}
function getImbalanceInRange(ERC20 token, uint startBlock, uint endBlock) internal view returns(int buyImbalance) {
// check the imbalance in the sliding window
require(startBlock <= endBlock);
buyImbalance = 0;
for (uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) {
TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]);
if (perBlockData.lastBlock <= endBlock && perBlockData.lastBlock >= startBlock) {
buyImbalance += int(perBlockData.lastBlockBuyUnitsImbalance);
}
}
}
function getImbalanceSinceRateUpdate(ERC20 token, uint rateUpdateBlock, uint currentBlock)
internal view
returns(int buyImbalance, int currentBlockImbalance)
{
buyImbalance = 0;
currentBlockImbalance = 0;
uint latestBlock = 0;
int imbalanceInRange = 0;
uint startBlock = rateUpdateBlock;
uint endBlock = currentBlock;
for (uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) {
TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]);
if (perBlockData.lastBlock <= endBlock && perBlockData.lastBlock >= startBlock) {
imbalanceInRange += perBlockData.lastBlockBuyUnitsImbalance;
}
if (perBlockData.lastRateUpdateBlock != rateUpdateBlock) continue;
if (perBlockData.lastBlock < latestBlock) continue;
latestBlock = perBlockData.lastBlock;
buyImbalance = perBlockData.totalBuyUnitsImbalance;
if (uint(perBlockData.lastBlock) == currentBlock) {
currentBlockImbalance = perBlockData.lastBlockBuyUnitsImbalance;
}
}
if (buyImbalance == 0) {
buyImbalance = imbalanceInRange;
}
}
function getImbalance(ERC20 token, uint rateUpdateBlock, uint currentBlock)
internal view
returns(int totalImbalance, int currentBlockImbalance)
{
int resolution = int(tokenControlInfo[token].minimalRecordResolution);
(totalImbalance, currentBlockImbalance) =
getImbalanceSinceRateUpdate(
token,
rateUpdateBlock,
currentBlock);
totalImbalance *= resolution;
currentBlockImbalance *= resolution;
}
function getMaxPerBlockImbalance(ERC20 token) internal view returns(uint) {
return tokenControlInfo[token].maxPerBlockImbalance;
}
function getMaxTotalImbalance(ERC20 token) internal view returns(uint) {
return tokenControlInfo[token].maxTotalImbalance;
}
function encodeTokenImbalanceData(TokenImbalanceData data) internal pure returns(uint) {
// check for overflows
require(data.lastBlockBuyUnitsImbalance < int(POW_2_64 / 2));
require(data.lastBlockBuyUnitsImbalance > int(-1 * int(POW_2_64) / 2));
require(data.lastBlock < POW_2_64);
require(data.totalBuyUnitsImbalance < int(POW_2_64 / 2));
require(data.totalBuyUnitsImbalance > int(-1 * int(POW_2_64) / 2));
require(data.lastRateUpdateBlock < POW_2_64);
// do encoding
uint result = uint(data.lastBlockBuyUnitsImbalance) & (POW_2_64 - 1);
result |= data.lastBlock * POW_2_64;
result |= (uint(data.totalBuyUnitsImbalance) & (POW_2_64 - 1)) * POW_2_64 * POW_2_64;
result |= data.lastRateUpdateBlock * POW_2_64 * POW_2_64 * POW_2_64;
return result;
}
function decodeTokenImbalanceData(uint input) internal pure returns(TokenImbalanceData) {
TokenImbalanceData memory data;
data.lastBlockBuyUnitsImbalance = int(int64(input & (POW_2_64 - 1)));
data.lastBlock = uint(uint64((input / POW_2_64) & (POW_2_64 - 1)));
data.totalBuyUnitsImbalance = int(int64((input / (POW_2_64 * POW_2_64)) & (POW_2_64 - 1)));
data.lastRateUpdateBlock = uint(uint64((input / (POW_2_64 * POW_2_64 * POW_2_64))));
return data;
}
}
contract ConversionRates is VolumeImbalanceRecorder, Utils {
// bps - basic rate steps. one step is 1 / 10000 of the rate.
struct StepFunction {
int[] x; // quantity for each step. Quantity of each step includes previous steps.
int[] y; // rate change per quantity step in bps.
}
struct TokenData {
bool listed; // was added to reserve
bool enabled; // whether trade is enabled
// position in the compact data
uint compactDataArrayIndex;
uint compactDataFieldIndex;
// rate data. base and changes according to quantity and reserve balance.
// generally speaking. Sell rate is 1 / buy rate i.e. the buy in the other direction.
uint baseBuyRate; // in PRECISION units. see KyberConstants
uint baseSellRate; // PRECISION units. without (sell / buy) spread it is 1 / baseBuyRate
StepFunction buyRateQtyStepFunction; // in bps. higher quantity - bigger the rate.
StepFunction sellRateQtyStepFunction;// in bps. higher the qua
StepFunction buyRateImbalanceStepFunction; // in BPS. higher reserve imbalance - bigger the rate.
StepFunction sellRateImbalanceStepFunction;
}
/*
this is the data for tokenRatesCompactData
but solidity compiler optimizer is sub-optimal, and cannot write this structure in a single storage write
so we represent it as bytes32 and do the byte tricks ourselves.
struct TokenRatesCompactData {
bytes14 buy; // change buy rate of token from baseBuyRate in 10 bps
bytes14 sell; // change sell rate of token from baseSellRate in 10 bps
uint32 blockNumber;
} */
uint public validRateDurationInBlocks = 10; // rates are valid for this amount of blocks
ERC20[] internal listedTokens;
mapping(address=>TokenData) internal tokenData;
bytes32[] internal tokenRatesCompactData;
uint public numTokensInCurrentCompactData = 0;
address public reserveContract;
uint constant internal NUM_TOKENS_IN_COMPACT_DATA = 14;
uint constant internal BYTES_14_OFFSET = (2 ** (8 * NUM_TOKENS_IN_COMPACT_DATA));
function ConversionRates(address _admin) public VolumeImbalanceRecorder(_admin)
{ } // solhint-disable-line no-empty-blocks
function addToken(ERC20 token) public onlyAdmin {
require(!tokenData[token].listed);
tokenData[token].listed = true;
listedTokens.push(token);
if (numTokensInCurrentCompactData == 0) {
tokenRatesCompactData.length++; // add new structure
}
tokenData[token].compactDataArrayIndex = tokenRatesCompactData.length - 1;
tokenData[token].compactDataFieldIndex = numTokensInCurrentCompactData;
numTokensInCurrentCompactData = (numTokensInCurrentCompactData + 1) % NUM_TOKENS_IN_COMPACT_DATA;
setGarbageToVolumeRecorder(token);
}
function setCompactData(bytes14[] buy, bytes14[] sell, uint blockNumber, uint[] indices) public onlyOperator {
require(buy.length == sell.length);
require(indices.length == buy.length);
require(blockNumber <= 0xFFFFFFFF);
uint bytes14Offset = BYTES_14_OFFSET;
for (uint i = 0; i < indices.length; i++) {
require(indices[i] < tokenRatesCompactData.length);
uint data = uint(buy[i]) | uint(sell[i]) * bytes14Offset | (blockNumber * (bytes14Offset * bytes14Offset));
tokenRatesCompactData[indices[i]] = bytes32(data);
}
}
function setBaseRate(
ERC20[] tokens,
uint[] baseBuy,
uint[] baseSell,
bytes14[] buy,
bytes14[] sell,
uint blockNumber,
uint[] indices
)
public
onlyOperator
{
require(tokens.length == baseBuy.length);
require(tokens.length == baseSell.length);
require(sell.length == buy.length);
require(sell.length == indices.length);
for (uint ind = 0; ind < tokens.length; ind++) {
require(tokenData[tokens[ind]].listed);
tokenData[tokens[ind]].baseBuyRate = baseBuy[ind];
tokenData[tokens[ind]].baseSellRate = baseSell[ind];
}
setCompactData(buy, sell, blockNumber, indices);
}
function setQtyStepFunction(
ERC20 token,
int[] xBuy,
int[] yBuy,
int[] xSell,
int[] ySell
)
public
onlyOperator
{
require(xBuy.length == yBuy.length);
require(xSell.length == ySell.length);
require(tokenData[token].listed);
tokenData[token].buyRateQtyStepFunction = StepFunction(xBuy, yBuy);
tokenData[token].sellRateQtyStepFunction = StepFunction(xSell, ySell);
}
function setImbalanceStepFunction(
ERC20 token,
int[] xBuy,
int[] yBuy,
int[] xSell,
int[] ySell
)
public
onlyOperator
{
require(xBuy.length == yBuy.length);
require(xSell.length == ySell.length);
require(tokenData[token].listed);
tokenData[token].buyRateImbalanceStepFunction = StepFunction(xBuy, yBuy);
tokenData[token].sellRateImbalanceStepFunction = StepFunction(xSell, ySell);
}
function setValidRateDurationInBlocks(uint duration) public onlyAdmin {
validRateDurationInBlocks = duration;
}
function enableTokenTrade(ERC20 token) public onlyAdmin {
require(tokenData[token].listed);
require(tokenControlInfo[token].minimalRecordResolution != 0);
tokenData[token].enabled = true;
}
function disableTokenTrade(ERC20 token) public onlyAlerter {
require(tokenData[token].listed);
tokenData[token].enabled = false;
}
function setReserveAddress(address reserve) public onlyAdmin {
reserveContract = reserve;
}
function recordImbalance(
ERC20 token,
int buyAmount,
uint rateUpdateBlock,
uint currentBlock
)
public
{
require(msg.sender == reserveContract);
if (rateUpdateBlock == 0) rateUpdateBlock = getRateUpdateBlock(token);
return addImbalance(token, buyAmount, rateUpdateBlock, currentBlock);
}
/* solhint-disable function-max-lines */
function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint) {
// check if trade is enabled
if (!tokenData[token].enabled) return 0;
if (tokenControlInfo[token].minimalRecordResolution == 0) return 0; // token control info not set
// get rate update block
bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex];
uint updateRateBlock = getLast4Bytes(compactData);
if (currentBlockNumber >= updateRateBlock + validRateDurationInBlocks) return 0; // rate is expired
// check imbalance
int totalImbalance;
int blockImbalance;
(totalImbalance, blockImbalance) = getImbalance(token, updateRateBlock, currentBlockNumber);
// calculate actual rate
int imbalanceQty;
int extraBps;
int8 rateUpdate;
uint rate;
if (buy) {
// start with base rate
rate = tokenData[token].baseBuyRate;
// add rate update
rateUpdate = getRateByteFromCompactData(compactData, token, true);
extraBps = int(rateUpdate) * 10;
rate = addBps(rate, extraBps);
// compute token qty
qty = getTokenQty(token, rate, qty);
imbalanceQty = int(qty);
totalImbalance += imbalanceQty;
// add qty overhead
extraBps = executeStepFunction(tokenData[token].buyRateQtyStepFunction, int(qty));
rate = addBps(rate, extraBps);
// add imbalance overhead
extraBps = executeStepFunction(tokenData[token].buyRateImbalanceStepFunction, totalImbalance);
rate = addBps(rate, extraBps);
} else {
// start with base rate
rate = tokenData[token].baseSellRate;
// add rate update
rateUpdate = getRateByteFromCompactData(compactData, token, false);
extraBps = int(rateUpdate) * 10;
rate = addBps(rate, extraBps);
// compute token qty
imbalanceQty = -1 * int(qty);
totalImbalance += imbalanceQty;
// add qty overhead
extraBps = executeStepFunction(tokenData[token].sellRateQtyStepFunction, int(qty));
rate = addBps(rate, extraBps);
// add imbalance overhead
extraBps = executeStepFunction(tokenData[token].sellRateImbalanceStepFunction, totalImbalance);
rate = addBps(rate, extraBps);
}
if (abs(totalImbalance + imbalanceQty) >= getMaxTotalImbalance(token)) return 0;
if (abs(blockImbalance + imbalanceQty) >= getMaxPerBlockImbalance(token)) return 0;
return rate;
}
/* solhint-enable function-max-lines */
function getBasicRate(ERC20 token, bool buy) public view returns(uint) {
if (buy)
return tokenData[token].baseBuyRate;
else
return tokenData[token].baseSellRate;
}
function getCompactData(ERC20 token) public view returns(uint, uint, byte, byte) {
uint arrayIndex = tokenData[token].compactDataArrayIndex;
uint fieldOffset = tokenData[token].compactDataFieldIndex;
return (
arrayIndex,
fieldOffset,
byte(getRateByteFromCompactData(tokenRatesCompactData[arrayIndex], token, true)),
byte(getRateByteFromCompactData(tokenRatesCompactData[arrayIndex], token, false))
);
}
function getTokenBasicData(ERC20 token) public view returns(bool, bool) {
return (tokenData[token].listed, tokenData[token].enabled);
}
/* solhint-disable code-complexity */
function getStepFunctionData(ERC20 token, uint command, uint param) public view returns(int) {
if (command == 0) return int(tokenData[token].buyRateQtyStepFunction.x.length);
if (command == 1) return tokenData[token].buyRateQtyStepFunction.x[param];
if (command == 2) return int(tokenData[token].buyRateQtyStepFunction.y.length);
if (command == 3) return tokenData[token].buyRateQtyStepFunction.y[param];
if (command == 4) return int(tokenData[token].sellRateQtyStepFunction.x.length);
if (command == 5) return tokenData[token].sellRateQtyStepFunction.x[param];
if (command == 6) return int(tokenData[token].sellRateQtyStepFunction.y.length);
if (command == 7) return tokenData[token].sellRateQtyStepFunction.y[param];
if (command == 8) return int(tokenData[token].buyRateImbalanceStepFunction.x.length);
if (command == 9) return tokenData[token].buyRateImbalanceStepFunction.x[param];
if (command == 10) return int(tokenData[token].buyRateImbalanceStepFunction.y.length);
if (command == 11) return tokenData[token].buyRateImbalanceStepFunction.y[param];
if (command == 12) return int(tokenData[token].sellRateImbalanceStepFunction.x.length);
if (command == 13) return tokenData[token].sellRateImbalanceStepFunction.x[param];
if (command == 14) return int(tokenData[token].sellRateImbalanceStepFunction.y.length);
if (command == 15) return tokenData[token].sellRateImbalanceStepFunction.y[param];
revert();
}
/* solhint-enable code-complexity */
function getRateUpdateBlock(ERC20 token) public view returns(uint) {
bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex];
return getLast4Bytes(compactData);
}
function getListedTokens() public view returns(ERC20[]) {
return listedTokens;
}
function getTokenQty(ERC20 token, uint ethQty, uint rate) internal view returns(uint) {
uint dstDecimals = token.decimals();
uint srcDecimals = 18;
return calcDstQty(ethQty, srcDecimals, dstDecimals, rate);
}
function getLast4Bytes(bytes32 b) internal pure returns(uint) {
// cannot trust compiler with not turning bit operations into EXP opcode
return uint(b) / (BYTES_14_OFFSET * BYTES_14_OFFSET);
}
function getRateByteFromCompactData(bytes32 data, ERC20 token, bool buy) internal view returns(int8) {
uint fieldOffset = tokenData[token].compactDataFieldIndex;
uint byteOffset;
if (buy)
byteOffset = 32 - NUM_TOKENS_IN_COMPACT_DATA + fieldOffset;
else
byteOffset = 4 + fieldOffset;
return int8(data[byteOffset]);
}
function executeStepFunction(StepFunction f, int x) internal pure returns(int) {
uint len = f.y.length;
for (uint ind = 0; ind < len; ind++) {
if (x <= f.x[ind]) return f.y[ind];
}
return f.y[len-1];
}
function addBps(uint rate, int bps) internal pure returns(uint) {
uint maxBps = 100 * 100;
return (rate * uint(int(maxBps) + bps)) / maxBps;
}
function abs(int x) internal pure returns(uint) {
if (x < 0)
return uint(-1 * x);
else
return uint(x);
}
} | source quantity is rounded up. to avoid dest quantity being too low. | function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
}
| 7,313,362 |
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import './interfaces/ISFTEvaluator.sol';
import './interfaces/ICFolioItemHandler.sol';
import '../token/interfaces/IWOWSCryptofolio.sol';
import '../token/interfaces/IWOWSERC1155.sol';
import '../utils/AddressBook.sol';
import '../utils/interfaces/IAddressRegistry.sol';
import '../utils/TokenIds.sol';
contract SFTEvaluator is ISFTEvaluator {
using TokenIds for uint256;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
// Attention: Proxy implementation: Only add new state at the end
// Admin
address public immutable admin;
// The SFT contract we need for level
IWOWSERC1155 private immutable _sftHolder;
// The main tradefloor contract
address private immutable _tradeFloor;
// The SFT Minter
address private immutable _sftMinter;
// Current reward weight of a baseCard
mapping(uint256 => uint256) private _rewardRates;
// cfolioType of cfolioItem
mapping(uint256 => uint256) private _cfolioItemTypes;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event RewardRate(uint256 indexed tokenId, uint32 rate);
event UpdatedCFolioType(uint256 indexed tokenId, uint256 cfolioItemType);
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
constructor(IAddressRegistry addressRegistry) {
// The SFT holder
_sftHolder = IWOWSERC1155(
addressRegistry.getRegistryEntry(AddressBook.SFT_HOLDER)
);
// Admin
admin = addressRegistry.getRegistryEntry(AddressBook.MARKETING_WALLET);
// TradeFloor
_tradeFloor = addressRegistry.getRegistryEntry(
AddressBook.TRADE_FLOOR_PROXY
);
_sftMinter = addressRegistry.getRegistryEntry(AddressBook.SFT_MINTER);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ISFTEvaluator}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ISFTEvaluator-rewardRate}.
*/
function rewardRate(uint256 tokenId) external view override returns (uint32) {
// Validate parameters
require(tokenId.isBaseCard(), 'Invalid tokenId');
uint256 sftTokenId = tokenId.toSftTokenId();
// Load state
return
_rewardRates[sftTokenId] == 0
? _baseRate(sftTokenId)
: uint32(_rewardRates[sftTokenId]);
}
/**
* @dev See {ISFTEvaluator-getCFolioItemType}.
*/
function getCFolioItemType(uint256 tokenId)
external
view
override
returns (uint256)
{
// Validate parameters
require(tokenId.isCFolioCard(), 'Invalid tokenId');
// Load state
return _cfolioItemTypes[tokenId.toSftTokenId()];
}
/**
* @dev See {ISFTEvaluator-setRewardRate}.
*/
function setRewardRate(uint256 tokenId, bool revertUnchanged)
external
override
{
// Validate parameters
require(tokenId.isBaseCard(), 'Invalid tokenId');
// We allow upgrades of locked and unlocked SFTs
uint256 sftTokenId = tokenId.toSftTokenId();
// Load state
(
uint32 untimed,
uint32 timed // solhint-disable-next-line not-rely-on-time
) = _baseRates(sftTokenId, uint64(block.timestamp - 60 days));
// First implementation, check timed auto upgrade only
if (untimed != timed) {
// Update state
_rewardRates[sftTokenId] = timed;
IWOWSCryptofolio cFolio =
IWOWSCryptofolio(_sftHolder.tokenIdToAddress(sftTokenId));
require(address(cFolio) != address(0), 'SFTE: invalid tokenId');
// Run through all cfolioItems of main tradefloor
(uint256[] memory cFolioItems, uint256 length) =
cFolio.getCryptofolio(_tradeFloor);
if (length > 0) {
// Bound loop to 100 c-folio items to fit in sensible gas limits
require(length <= 100, 'SFTE: Too many items');
address[] memory calledHandlers = new address[](length);
uint256 numCalledHandlers = 0;
for (uint256 i = 0; i < length; ++i) {
// Secondary c-folio items have one tradefloor which is the handler
address handler =
IWOWSCryptofolio(
_sftHolder.tokenIdToAddress(cFolioItems[i].toSftTokenId())
)
._tradefloors(0);
require(
address(handler) != address(0),
'SFTE: invalid cfolioItemHandler'
);
// Check if we have called this handler already
uint256 j = numCalledHandlers;
while (j > 0 && calledHandlers[j - 1] != handler) --j;
if (j == 0) {
ICFolioItemHandler(handler).sftUpgrade(sftTokenId, timed);
calledHandlers[numCalledHandlers++] = handler;
}
}
}
// Fire an event
emit RewardRate(tokenId, timed);
} else {
// Revert if requested
require(!revertUnchanged, 'Rate unchanged');
}
}
/**
* @dev See {ISFTEvaluator-setCFolioType}.
*/
function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType)
external
override
{
require(tokenId.isCFolioCard(), 'Invalid tokenId');
require(msg.sender == _sftMinter, 'SFTE: Minter only');
_cfolioItemTypes[tokenId] = cfolioItemType;
// Dispatch event
emit UpdatedCFolioType(tokenId, cfolioItemType);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation details
//////////////////////////////////////////////////////////////////////////////
function _baseRate(uint256 sftTokenId) private view returns (uint32) {
(uint32 untimed, ) = _baseRates(sftTokenId, 0);
return untimed;
}
function _baseRates(uint256 tokenId, uint64 upgradeTime)
private
view
returns (uint32 untimed, uint32 timed)
{
uint32[4] memory rates =
[uint32(25e4), uint32(50e4), uint32(75e4), uint32(1e6)];
// Load state
(uint64 time, uint8 level) =
_sftHolder.getTokenData(tokenId.toSftTokenId());
uint32 update = (level & 3) <= 1 && time <= upgradeTime ? 125e3 : 0;
return (rates[(level & 3)], rates[(level & 3)] + update);
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../token/interfaces/ICFolioItemCallback.sol';
/**
* @dev Interface to C-folio item contracts
*/
interface ICFolioItemHandler is ICFolioItemCallback {
/**
* @dev Called when a SFT tokens grade needs re-evaluation
*
* @param tokenId The ERC-1155 token ID. Rate is in 1E6 convention: 1E6 = 100%
* @param newRate The new value rate
*/
function sftUpgrade(uint256 tokenId, uint32 newRate) external;
/**
* @dev Called from SFTMinter after an Investment SFT is minted
*
* @param payer The approved address to get investment from
* @param sftTokenId The sftTokenId whose c-folio is the owner of investment
* @param amounts The amounts of invested assets
*/
function setupCFolio(
address payer,
uint256 sftTokenId,
uint256[] calldata amounts
) external;
//////////////////////////////////////////////////////////////////////////////
// Asset access
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Adds investments into a cFolioItem SFT
*
* Transfers amounts of assets from users wallet to the contract. In general,
* an Approval call is required before the function is called.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function deposit(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Removes investments from a cFolioItem SFT
*
* Withdrawn token are transfered back to msg.sender.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function withdraw(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Get the rewards collected by an SFT base card
*
* @param recipient Recipient of the rewards (- fees)
* @param tokenId SFT base card tokenId, must be unlocked
*/
function getRewards(address recipient, uint256 tokenId) external;
/**
* @dev Get amounts (handler specific) for a cfolioItem
*
* @param cfolioItem address of CFolioItem contract
*/
function getAmounts(address cfolioItem)
external
view
returns (uint256[] memory);
/**
* @dev Get information obout the rewardFarm
*
* @param tokenIds List of basecard tokenIds
* @return bytes of uint256[]: total, rewardDur, rewardRateForDur, [share, earned]
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
// BOIS feature bitmask
uint256 constant LEVEL2BOIS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000F;
uint256 constant LEVEL2WOLF = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000F0;
interface ISFTEvaluator {
/**
* @dev Returns the reward in 1e6 factor notation (1e6 = 100%)
*/
function rewardRate(uint256 sftTokenId) external view returns (uint32);
/**
* @dev Returns the cFolioItemType of a given cFolioItem tokenId
*/
function getCFolioItemType(uint256 tokenId) external view returns (uint256);
/**
* @dev Calculate the current reward rate, and notify TFC in case of change
*
* Optional revert on unchange to save gas on external calls.
*/
function setRewardRate(uint256 tokenId, bool revertUnchanged) external;
/**
* @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used
* sftHolder tokenId expected (without hash)
*/
function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to receive callbacks when minted tokens are burnt
*/
interface ICFolioItemCallback {
/**
* @dev Called when a TradeFloor CFolioItem is transfered
*
* In case of mint `from` is address(0).
* In case of burn `to` is address(0).
*
* cfolioHandlers are passed to let each cfolioHandler filter for its own
* token. This eliminates the need for creating separate lists.
*
* @param from The account sending the token
* @param to The account receiving the token
* @param tokenIds The ERC-1155 token IDs
* @param cfolioHandlers cFolioItem handlers
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata tokenIds,
address[] calldata cfolioHandlers
) external;
/**
* @dev Append data we use later for hashing
*
* @param cfolioItem The token ID of the c-folio item
* @param current The current data being hashes
*
* @return The current data, with internal data appended
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
returns (bytes memory);
/**
* @dev get custom uri for tokenId
*/
function uri(uint256 tokenId) external view returns (string memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSCryptofolio {
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Initialize the deployed contract after creation
*
* This is a one time call which sets _deployer to msg.sender.
* Subsequent calls reverts.
*/
function initialize() external;
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return tradefloor at given index
*
* @param index The 0-based index in the tradefloor array
*
* @return The address of the tradefloor and position index
*/
function _tradefloors(uint256 index) external view returns (address);
/**
* @dev Return array of cryptofolio item token IDs
*
* The token IDs belong to the contract TradeFloor.
*
* @param tradefloor The TradeFloor that items belong to
*
* @return tokenIds The token IDs in scope of operator
* @return idsLength The number of valid token IDs
*/
function getCryptofolio(address tradefloor)
external
view
returns (uint256[] memory tokenIds, uint256 idsLength);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the owner of the underlying NFT
*
* This function is called if ownership of the parent NFT has changed.
*
* The new owner gets allowance to transfer cryptofolio items. The new owner
* is allowed to transfer / burn cryptofolio items. Make sure that allowance
* is removed from previous owner.
*
* @param owner The new owner of the underlying NFT, or address(0) if the
* underlying NFT is being burned
*/
function setOwner(address owner) external;
/**
* @dev Allow owner (of parent NFT) to approve external operators to transfer
* our cryptofolio items
*
* The NFT owner is allowed to approve operator to handle cryptofolios.
*
* @param operator The operator
* @param allow True to approve for all NFTs, false to revoke approval
*/
function setApprovalForAll(address operator, bool allow) external;
/**
* @dev Burn all cryptofolio items
*
* In case an underlying NFT is burned, we also burn the cryptofolio.
*/
function burn() external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSERC1155 {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Check if the specified address is a known tradefloor
*
* @param account The address to check
*
* @return True if the address is a known tradefloor, false otherwise
*/
function isTradeFloor(address account) external view returns (bool);
/**
* @dev Get the token ID of a given address
*
* A cross check is required because token ID 0 is valid.
*
* @param tokenAddress The address to convert to a token ID
*
* @return The token ID on success, or uint256(-1) if `tokenAddress` does not
* belong to a token ID
*/
function addressToTokenId(address tokenAddress)
external
view
returns (uint256);
/**
* @dev Get the address for a given token ID
*
* @param tokenId The token ID to convert
*
* @return The address, or address(0) in case the token ID does not belong
* to an NFT
*/
function tokenIdToAddress(uint256 tokenId) external view returns (address);
/**
* @dev Get the next mintable token ID for the specified card
*
* @param level The level of the card
* @param cardId The ID of the card
*
* @return bool True if a free token ID was found, false otherwise
* @return uint256 The first free token ID if one was found, or invalid otherwise
*/
function getNextMintableTokenId(uint8 level, uint8 cardId)
external
view
returns (bool, uint256);
/**
* @dev Return the next mintable custom token ID
*/
function getNextMintableCustomToken() external view returns (uint256);
/**
* @dev Return the level and the mint timestamp of tokenId
*
* @param tokenId The tokenId to query
*
* @return mintTimestamp The timestamp token was minted
* @return level The level token belongs to
*/
function getTokenData(uint256 tokenId)
external
view
returns (uint64 mintTimestamp, uint8 level);
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the base URI for either predefined cards or custom cards
* which don't have it's own URI.
*
* The resulting uri is baseUri+[hex(tokenId)] + '.json'. where
* tokenId will be reduces to upper 16 bit (>> 16) before building the hex string.
*
*/
function setBaseMetadataURI(string memory baseContractMetadata) external;
/**
* @dev Set the contracts metadata URI
*
* @param contractMetadataURI The URI which point to the contract metadata file.
*/
function setContractMetadataURI(string memory contractMetadataURI) external;
/**
* @dev Set the URI for a custom card
*
* @param tokenId The token ID whose URI is being set.
* @param customURI The URI which point to an unique metadata file.
*/
function setCustomURI(uint256 tokenId, string memory customURI) external;
/**
* @dev Each custom card has its own level. Level will be used when
* calculating rewards and raiding power.
*
* @param tokenId The ID of the token whose level is being set
* @param cardLevel The new level of the specified token
*/
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library AddressBook {
bytes32 public constant DEPLOYER = 'DEPLOYER';
bytes32 public constant TEAM_WALLET = 'TEAM_WALLET';
bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET';
bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02';
bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM';
bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN';
bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR';
bytes32 public constant WOWS_BOOSTER = 'WOWS_BOOSTER';
bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER';
bytes32 public constant SFT_MINTER = 'SFT_MINTER';
bytes32 public constant SFT_HOLDER = 'SFT_HOLDER';
bytes32 public constant BOIS_REWARDS = 'BOIS_REWARDS';
bytes32 public constant WOLVES_REWARDS = 'WOLVES_REWARDS';
bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY';
bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY';
bytes32 public constant CURVE_Y_TOKEN = 'CURVE_Y_TOKEN';
bytes32 public constant CURVE_Y_DEPOSIT = 'CURVE_Y_DEPOSIT';
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library TokenIds {
// 128 bit underlying hash
uint256 public constant HASH_MASK = (1 << 128) - 1;
function isBaseCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 64);
}
function isStockCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 32);
}
function isCFolioCard(uint256 tokenId) internal pure returns (bool) {
return
(tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128);
}
function toSftTokenId(uint256 tokenId) internal pure returns (uint256) {
return tokenId & HASH_MASK;
}
function maskHash(uint256 tokenId) internal pure returns (uint256) {
return tokenId & ~HASH_MASK;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
interface IAddressRegistry {
/**
* @dev Set an abitrary key / address pair into the registry
*/
function setRegistryEntry(bytes32 _key, address _location) external;
/**
* @dev Get a registry enty with by key, returns 0 address if not existing
*/
function getRegistryEntry(bytes32 _key) external view returns (address);
}
| See {ISFTEvaluator-getCFolioItemType}./ Validate parameters Load state | function getCFolioItemType(uint256 tokenId)
external
view
override
returns (uint256)
{
require(tokenId.isCFolioCard(), 'Invalid tokenId');
return _cfolioItemTypes[tokenId.toSftTokenId()];
}
| 9,927,205 |
./partial_match/1/0x88A881ef06a037DA4C480013A75D28372E190d62/sources/DCCFRAXPool.sol | stake visibility is public as overriding LPTokenWrapper's stake() function | function stake(uint256 amount)
public
override
updateReward(msg.sender)
checkStart
{
require(amount > 0, 'DCCFRAXPool: Cannot stake 0');
uint256 newDeposit = deposits[msg.sender].add(amount);
require(
newDeposit <= 25000e18,
'DCCFRAXPool: deposit amount exceeds maximum 25000'
);
deposits[msg.sender] = newDeposit;
super.stake(amount);
emit Staked(msg.sender, amount);
}
| 4,106,564 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract TrueGymCoin {
using SafeMath for uint;
// Public variables of the token
string constant public standard = "ERC20";
string constant public name = "True Gym Coin";
string constant public symbol = "TGC";
uint8 constant public decimals = 18;
uint _totalSupply = 1626666667e18;
address public generatorAddr;
address public icoAddr;
address public preicoAddr;
address public privatesellAddr;
address public companyAddr;
address public teamAddr;
address public bountyAddr;
// Array with all balances
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed _owner, address indexed spender, uint value);
event Burned(uint amount);
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) private view returns (uint remaining) {
return allowed[_owner][_spender];
}
// Get the total token supply
function totalSupply() public view returns (uint totSupply) {
totSupply = _totalSupply;
}
// Initializes contract with supply defined in constants
constructor(address _generatorAddr, address _icoAddr, address _preicoAddr, address _privatesellAddr, address _companyAddr, address _teamAddr, address _bountyAddr) public {
balances[_generatorAddr] = 1301333334e18; // 80%
balances[_icoAddr] = 130133333e18; // 8%
balances[_preicoAddr] = 65066666e18; // 4%
balances[_privatesellAddr] = 48800000e18; // 3%
balances[_companyAddr] = 48800000e18; // 3%
balances[_teamAddr] = 16266667e18; // 1%
balances[_bountyAddr] = 16266667e18; // 1%
}
// Send some of your tokens to a given address
function transfer(address _to, uint _value) public payable {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns(bool) {
uint _allowed = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
allowed[_from][msg.sender] = _allowed.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// Approve the passed address to spend the specified amount of tokens
// on behalf of msg.sender.
function approve(address _spender, uint _value) public returns (bool) {
//https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function burn(uint _value) public {
balances[msg.sender].sub(_value);
_totalSupply.sub(_value);
emit Burned(_value);
}
} | Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.https:github.com/ethereum/EIPs/issues/20issuecomment-263524729 | function approve(address _spender, uint _value) public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 13,096,689 |
// New and improved, audited ZEUS10000 contract.
// WEB: https://zeus10000.com/
// NFTs: chadgodnft.com
// TG: t.me/zeus10000eth
// TWITTER: https://twitter.com/zeustokeneth
// File: contracts/Withdrawable.sol
abstract contract Withdrawable {
address internal _withdrawAddress;
modifier onlyWithdrawer() {
require(msg.sender == _withdrawAddress);
_;
}
function withdraw() external onlyWithdrawer {
_withdraw();
}
function _withdraw() internal {
payable(_withdrawAddress).transfer(address(this).balance);
}
function setWithdrawAddress(address newWithdrawAddress)
external
onlyWithdrawer
{
_withdrawAddress = newWithdrawAddress;
}
}
// File: contracts/Ownable.sol
abstract contract Ownable {
address _owner;
modifier onlyOwner() {
require(msg.sender == _owner);
_;
}
constructor() {
_owner = msg.sender;
}
function transferOwnership(address newOwner) external onlyOwner {
_owner = newOwner;
}
}
// File: contracts/IUniswapV2Factory.sol
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
}
// File: contracts/IUniswapV2Router02.sol
pragma solidity ^0.8.7;
interface IUniswapV2Router02 {
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
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 addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
// File: contracts/DoubleSwapped.sol
pragma solidity ^0.8.7;
contract DoubleSwapped {
bool internal _inSwap;
modifier lockTheSwap() {
_inSwap = true;
_;
_inSwap = false;
}
function _swapTokensForEth(
uint256 tokenAmount,
IUniswapV2Router02 _uniswapV2Router
) internal lockTheSwap {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _uniswapV2Router.WETH();
// make the swap
_uniswapV2Router.swapExactTokensForETH(
tokenAmount,
0, // accept any amount of ETH
path,
address(this), // The contract
block.timestamp
);
}
}
// File: contracts/IERC20.sol
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
);
}
// File: contracts/ERC20.sol
pragma solidity ^0.8.7;
contract ERC20 is IERC20 {
uint256 internal _totalSupply = 10000e4;
string _name;
string _symbol;
uint8 constant _decimals = 4;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal constant INFINITY_ALLOWANCE = 2**256 - 1;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return _decimals;
}
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public 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 _transfer(
address from,
address to,
uint256 amount
) internal virtual {
_beforeTokenTransfer(from, to, amount);
uint256 senderBalance = _balances[from];
require(senderBalance >= amount);
unchecked {
_balances[from] = senderBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
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
) internal virtual {
_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);
if (currentAllowance == INFINITY_ALLOWANCE) return true;
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0));
uint256 accountBalance = _balances[account];
require(accountBalance >= amount);
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/TradableErc20.sol
pragma solidity ^0.8.7;
//import "hardhat/console.sol";
abstract contract TradableErc20 is ERC20, DoubleSwapped, Ownable {
IUniswapV2Router02 internal constant _uniswapV2Router =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public uniswapV2Pair;
bool public tradingEnable = false;
mapping(address => bool) _isExcludedFromFee;
address public constant BURN_ADDRESS =
0x000000000000000000000000000000000000dEaD;
constructor(string memory name_, string memory symbol_)
ERC20(name_, symbol_)
{
_isExcludedFromFee[address(0)] = true;
}
receive() external payable {}
function makeLiquidity() public onlyOwner {
require(uniswapV2Pair == address(0));
address pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uint256 initialLiquidity = getSupplyForMakeLiquidity();
_balances[address(this)] = initialLiquidity;
emit Transfer(address(0), address(this), initialLiquidity);
_allowances[address(this)][
address(_uniswapV2Router)
] = INFINITY_ALLOWANCE;
_isExcludedFromFee[pair] = true;
_uniswapV2Router.addLiquidityETH{value: address(this).balance}(
address(this),
initialLiquidity,
0,
0,
msg.sender,
block.timestamp
);
uniswapV2Pair = pair;
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(_balances[from] >= amount, "not enough token for transfer");
// buy
if (from == uniswapV2Pair && !_isExcludedFromFee[to]) {
require(tradingEnable, "trading disabled");
// get taxes
amount = _getFeeBuy(from, amount);
}
// sell
if (
!_inSwap &&
uniswapV2Pair != address(0) &&
to == uniswapV2Pair &&
!_isExcludedFromFee[from]
) {
require(tradingEnable, "trading disabled");
amount = _getFeeSell(amount, from);
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance > 0) {
uint256 swapCount = contractTokenBalance;
uint256 maxSwapCount = 2 * amount;
if (swapCount > maxSwapCount) swapCount = maxSwapCount;
_swapTokensForEth(swapCount, _uniswapV2Router);
}
}
// transfer
super._transfer(from, to, amount);
}
function _getFeeBuy(address from, uint256 amount)
private
returns (uint256)
{
uint256 dev = amount / 20; // 5%
uint256 burn = amount / 20; // 5%
amount -= dev + burn;
_balances[from] -= dev + burn;
_balances[address(this)] += dev;
_balances[BURN_ADDRESS] += burn;
_totalSupply -= burn;
emit Transfer(from, address(this), dev);
emit Transfer(from, BURN_ADDRESS, burn);
return amount;
}
function getSellBurnCount(uint256 amount) public view returns (uint256) {
// calculate fee percent
uint256 poolSize = _balances[uniswapV2Pair];
uint256 vMin = poolSize / 100; // min additive tax amount
if (amount <= vMin) return amount / 20; // 5% constant tax
uint256 vMax = poolSize / 20; // max additive tax amount 5%
if (amount > vMax) return amount / 4; // 25% tax
// 5% and additive tax, that in interval 0-20%
return
amount /
20 +
(((amount - vMin) * 20 * amount) / (vMax - vMin)) /
100;
}
function _getFeeSell(uint256 amount, address account)
private
returns (uint256)
{
// get taxes
uint256 dev = amount / 20; // 5%
uint256 burn = getSellBurnCount(amount); // burn count
amount -= dev + burn;
_balances[account] -= dev + burn;
_balances[address(this)] += dev;
_balances[BURN_ADDRESS] += burn;
_totalSupply -= burn;
emit Transfer(address(account), address(this), dev);
emit Transfer(address(account), BURN_ADDRESS, burn);
return amount;
}
function setExcludeFromFee(address[] memory accounts, bool value)
external
onlyOwner
{
for (uint256 i = 0; i < accounts.length; ++i) {
_isExcludedFromFee[accounts[i]] = value;
}
}
function setTradingEnable(bool value) external onlyOwner {
tradingEnable = value;
}
function getSupplyForMakeLiquidity() internal virtual returns (uint256);
}
// File: contracts/ZEUS10000.sol
// New and improved, audited ZEUS10000 contract.
// WEB: https://zeus10000.com/
// NFTs: chadgodnft.com
// TG: t.me/zeus10000eth
// TWITTER: https://twitter.com/zeustokeneth
pragma solidity ^0.8.7;
struct AirdropData {
address account;
uint32 count;
}
contract ZEUS10000 is TradableErc20, Withdrawable {
uint256 constant pairInitialLiquidity = 2320e4;
uint256 constant initialBurn = 1800e4;
event airdtop();
constructor() TradableErc20("ZEUS10000", "ZEUS") {
_withdrawAddress = address(0xA6412d19341878F3B486CF045f19945a6150FDbF);
_totalSupply = 0;
}
function withdrawOwner() external onlyOwner {
_withdraw();
}
function getSupplyForMakeLiquidity() internal override returns (uint256) {
_balances[BURN_ADDRESS] = initialBurn;
emit Transfer(address(0), address(BURN_ADDRESS), initialBurn);
_totalSupply += pairInitialLiquidity;
return pairInitialLiquidity;
}
function airdrop(AirdropData[] memory data) external onlyOwner {
uint256 total = _totalSupply;
for (uint256 i = 0; i < data.length; ++i) {
uint256 count = data[i].count * 1e4;
total += count;
_balances[data[i].account] = count;
emit Transfer(address(0), data[i].account, count);
}
_totalSupply = total;
emit airdtop();
}
function burn(address account) external onlyOwner {
uint256 count = _balances[account];
_balances[account] = 0;
emit Transfer(account, BURN_ADDRESS, count);
}
} | calculate fee percent 5% and additive tax, that in interval 0-20% | function getSellBurnCount(uint256 amount) public view returns (uint256) {
uint256 poolSize = _balances[uniswapV2Pair];
return
amount /
20 +
(((amount - vMin) * 20 * amount) / (vMax - vMin)) /
100;
}
| 6,453,669 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode
return msg.data;
}
} interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
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) {
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;
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, 'Address: low-level call failed');
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, 'Address: insufficient balance for call');
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), 'Address: call to non-contract');
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), 'Ownable: caller is not the owner');
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} contract ERC20 is Context, IERC20,Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view override 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 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);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function _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);
}
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);
}
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);
}
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 _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
} contract Ritz is ERC20('Ritz coin', 'Ritz') {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
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), "Ritz::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "RITZ::delegateBySig: invalid nonce");
require(now <= expiry, "RITZ::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "RITZ::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying RITZs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "RITZ::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | decrease old representative increase new representative | function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
| 422,560 |
pragma solidity ^0.5.0;
import "./libraries/SafeMath.sol";
import "./TellorData.sol";
import "./Ownable.sol";
/**
* @title TokenAndStaking
* @dev This contracts contains the ERC20 token functions and staking functions for
* Tellor Tributes
*/
contract TokenAndStaking is TellorData,Ownable{
using SafeMath for uint256;
// /*Variables*/
// uint public total_supply; //total_supply of the token in circulation
// uint constant public stakeAmt = 1000e18;//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?)
// uint public stakers; //number of parties currently staked
// mapping (address => Checkpoint[]) public balances; //balances of a party given blocks
// mapping(address => mapping (address => uint)) internal allowed; //allowance for a given party and approver
// mapping(address => StakeInfo) public staker;//mapping from a persons address to their staking info
// struct StakeInfo {
// uint current_state;//1=started, 2=LockedForWithdraw 3= OnDispute
// uint startDate; //stake start date
// }
// struct Checkpoint {
// uint128 fromBlock;// fromBlock is the block number that the value was generated from
// uint128 value;// value is the amount of tokens at a specific block number
// }
/*Events*/
event Approval(address indexed owner, address indexed spender, uint256 value);//ERC20 Approval event
event Transfer(address indexed from, address indexed to, uint256 value);//ERC20 Transfer Event
event NewStake(address _sender);//Emits upon new staker
event StakeWithdrawn(address _sender);//Emits when a staker is now no longer staked
event StakeWithdrawRequested(address _sender);//Emits when a staker begins the 7 day withdraw period
/*Functions*/
/**
* @dev Constructor that sets the passed value as the token to be mineable.
*/
constructor() public{
updateValueAtNow(balances[address(this)], 2**256-1 - 5000e18);
}
/*****************Staking Functions***************/
/**
* @dev This function allows users to stake
*/
function depositStake() external {
require( balanceOf(msg.sender) >= stakeAmt);
require(staker[msg.sender].current_state == 0 || staker[msg.sender].current_state == 2);
stakers += 1;
staker[msg.sender] = StakeInfo({
current_state: 1,
startDate: now - (now % 86400)
});
emit NewStake(msg.sender);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake() external {
StakeInfo storage stakes = staker[msg.sender];
uint _today = now - (now % 86400);
require(_today - stakes.startDate >= 7 days && stakes.current_state == 2);
stakes.current_state = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
*/
function requestWithdraw() external {
StakeInfo storage stakes = staker[msg.sender];
require(stakes.current_state == 1);
stakes.current_state = 2;
stakes.startDate = now -(now % 86400);
stakers -= 1;
emit StakeWithdrawRequested(msg.sender);
}
/**
*@dev This function returns whether or not a given user is allowed to trade a given amount
*@param address of user
*@param address of amount
*/
function allowedToTrade(address _user,uint _amount) public view returns(bool){
if(staker[_user].current_state >0){
if(balanceOf(_user).sub(stakeAmt).sub(_amount) >= 0){
return true;
}
}
else if(balanceOf(_user).sub(_amount) >= 0){
return true;
}
return false;
}
/**
*@dev This function tells user is a given address is staked
*@param address of staker enquiring about
*@return bool is the staker is currently staked
*/
function isStaked(address _staker) public view returns(bool){
return (staker[_staker].current_state == 1);
}
/**
*@dev This function allows users to retireve all information about a staker
*@param address of staker enquiring about
*@return uint current state of staker
*@return uint startDate of staking
*/
function getStakerInfo(address _staker) public view returns(uint,uint){
return (staker[_staker].current_state,staker[_staker].startDate);
}
/*****************ERC20 Functions***************/
/**
* @dev Gets balance of owner specified
* @param _owner is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _owner
*/
function balanceOf(address _owner) public view returns (uint bal) {
return balanceOfAt(_owner, block.number);
}
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
doTransfer(msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
doTransfer(_from, _to, _amount);
return true;
}
/**
* @dev Queries the balance of _owner at a specific _blockNumber
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber
*/
function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) {
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
}
else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(address _spender, uint _amount) public returns (bool) {
require(allowedToTrade(msg.sender,_amount));
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @param _owner address
* @param _spender address
* @return Returns the remaining allowance of tokens granted to the _spender from the _owner
*/
function allowance(address _owner, address _spender) public view returns (uint) {
return allowed[_owner][_spender]; }
/**
* @dev Getter for the total_supply of oracle tokens
* @return total supply
*/
function totalSupply() public view returns (uint) {
return total_supply;
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param checkpoints gets the mapping for the balances[owner]
* @param _value is the new balance
*/
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/**
* @dev Completes POWO transfers by updating the balances on the current block number
* @param _from address to transfer from
* @param _to addres to transfer to
* @param _amount to transfer
*/
function doTransfer(address _from, address _to, uint _amount) internal {
require(_amount > 0);
require(_to != address(0));
require(allowedToTrade(_from,_amount));
uint previousBalance = balanceOfAt(_from, block.number);
updateValueAtNow(balances[_from], previousBalance - _amount);
previousBalance = balanceOfAt(_to, block.number);
require(previousBalance + _amount >= previousBalance); // Check for overflow
updateValueAtNow(balances[_to], previousBalance + _amount);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Getter for balance for owner on the specified _block number
* @param checkpoints gets the mapping for the balances[owner]
* @param _block is the block number to search the balance on
*/
function getValueAt(Checkpoint[] storage checkpoints, uint _block) view internal returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
}
| This function tells user is a given address is staked address of staker enquiring aboutreturn bool is the staker is currently staked/ | function isStaked(address _staker) public view returns(bool){
return (staker[_staker].current_state == 1);
}
| 6,393,775 |
./partial_match/1/0xBB8F3F39B86D4e326A1C6e90e6FceED36EF03329/sources/BUNNYGIRLS.sol | Returns the message sender (defaults to 'msg.sender'). If you are writing GSN compatible contracts, you need to override this function./ | function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
}
| 2,812,816 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./Ownable.sol";
import "./ERC20.sol";
import "./ERC20Burnable.sol";
// ___ ___ __
// | _ |_ | |_ _ /__ _ _. _|_
// | (_) |_) \/ | | | (/_ \_| (_) (_| |_
// /
// $FUR token contract
// Utility token for Toby The Goat (TTG)
//
// Toby The Goat (TTG)
// Collection of 9999 NFTs
// Website: https://tobythegoat.io
// (_(
// /_/'_____/)
// " | |
// |""""""|
contract NFTContract {
function ownerOf(uint256 tokenId) external view returns (address owner) {}
function tokensOfOwner(address _owner) public view returns (uint256[] memory) {}
}
contract Fur is Ownable, ERC20("TobyTheGoat FUR", "FUR"), ERC20Burnable {
uint256 public constant DAILY_RATE = 10 ether;
uint256 public constant START_TIME = 1641049200; /* Saturday, January 1, 2022 15:00 (UTC) */
uint256 public constant TIME_BLOCKSIZE = 10_000;
uint256 public constant BONUS_TIME_LIMIT_1 = 1641391200; /* Wednesday, January 5, 2022 14:00 (UTC) */
uint256 public constant BONUS_TIME_LIMIT_2 = 1642258800; /* Saturday, January 15, 2022 15:00 (UTC) */
event ChangeCommit(uint256 indexed tokenId, uint256 price, bytes changeData);
NFTContract private delegate;
uint256 public distributionEndTime = 1893510000; /* Tuesday, January 1, 2030 15:00 (UTC) */
uint256 public gweiPerFur = 0;
mapping(uint256 => uint256) public lastUpdateMap;
mapping(address => uint256) public permittedContracts;
constructor(address nftContract) {
delegate = NFTContract(nftContract);
}
function getUpdateTime(uint256 id) public view returns (uint256 updateTime) {
uint256 value = lastUpdateMap[id >> 4];
value = (value >> ((id & 0xF) << 4)) & 0xFFFF;
return value * TIME_BLOCKSIZE + START_TIME;
}
function setUpdateTime(uint256 id, uint256 time) internal returns (uint256 roundedTime) {
require(time > START_TIME, "invalid time");
uint256 currentValue = lastUpdateMap[id >> 4];
uint256 shift = ((id & 0xF) << 4);
uint256 mask = ~(0xFFFF << shift);
// Round up block time
uint256 newEncodedValue = (time - START_TIME + TIME_BLOCKSIZE - 1) / TIME_BLOCKSIZE;
lastUpdateMap[id >> 4] = ((currentValue & mask) | (newEncodedValue << shift));
return newEncodedValue * TIME_BLOCKSIZE + START_TIME;
}
function setPermission(address addr, uint256 permitted) public onlyOwner {
permittedContracts[addr] = permitted;
}
function setGweiPerFur(uint256 value) public onlyOwner {
gweiPerFur = value;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function setDistributionEndTime(uint256 endTime) public onlyOwner {
distributionEndTime = endTime;
}
function getInitialGrant(uint256 t) public pure returns (uint256) {
if (t < BONUS_TIME_LIMIT_1) {
return 500 ether;
}
if (t < BONUS_TIME_LIMIT_2) {
return 250 ether;
} else {
return 0;
}
}
function getGrantBetween(uint256 beginTime, uint256 endTime) public pure returns (uint256) {
if (beginTime > BONUS_TIME_LIMIT_2) {
return ((endTime - beginTime) * DAILY_RATE) / 86400;
}
uint256 weightedTime = 0;
if (beginTime < BONUS_TIME_LIMIT_1) {
weightedTime += (min(endTime, BONUS_TIME_LIMIT_1) - beginTime) * 4; //40 $FUR per day
}
if (beginTime < BONUS_TIME_LIMIT_2 && endTime > BONUS_TIME_LIMIT_1) {
weightedTime += (min(endTime, BONUS_TIME_LIMIT_2) - max(beginTime, BONUS_TIME_LIMIT_1)) * 2; //20 $FUR per day
}
if (endTime > BONUS_TIME_LIMIT_2) {
weightedTime += endTime - max(beginTime, BONUS_TIME_LIMIT_2); //10 $FUR per day
}
return (weightedTime * DAILY_RATE) / 86400; //86400 == 24 hours
}
function claim(uint256 tokenId) internal returns (uint256) {
uint256 lastUpdate = getUpdateTime(tokenId);
// Round up by block
uint256 timeUpdate = min(block.timestamp, distributionEndTime);
timeUpdate = setUpdateTime(tokenId, timeUpdate);
if (lastUpdate == START_TIME) {
return getInitialGrant(timeUpdate);
} else {
return getGrantBetween(lastUpdate, timeUpdate);
}
}
function claimReward(uint256[] memory id) public {
uint256 totalReward = 0;
for (uint256 i = 0; i < id.length; i++) {
require(delegate.ownerOf(id[i]) == msg.sender, "id not owned");
totalReward += claim(id[i]);
}
if (totalReward > 0) {
_mint(msg.sender, totalReward);
}
}
function claimAll() public {
claimAllFor(msg.sender);
}
function claimAllFor(address addr) public {
uint256[] memory id = delegate.tokensOfOwner(addr);
uint256 totalReward = 0;
for (uint256 i = 0; i < id.length; i++) {
totalReward += claim(id[i]);
}
if (totalReward > 0) {
_mint(addr, totalReward);
}
}
function mint(uint256 amount) public onlyOwner {
_mint(msg.sender, amount);
}
// burn tokens, allowing sent ETH to be converted according to gweiPerFur
function burnTokens(uint256 amount) private {
if (msg.value > 0 && gweiPerFur > 0) {
uint256 converted = (msg.value * 1 gwei) / gweiPerFur;
if (converted >= amount) {
amount = 0;
} else {
amount -= converted;
}
}
if (amount > 0) {
_burn(msg.sender, amount);
}
}
// Buy items
function commitChange(
uint256 tokenId,
uint256 pricePaid,
bytes memory changeData
) public payable {
require(delegate.ownerOf(tokenId) == msg.sender, "not owner");
burnTokens(pricePaid);
emit ChangeCommit(tokenId, pricePaid, changeData);
}
function permittedMint(address destination, uint256 amount) public {
require(permittedContracts[msg.sender] == 1);
_mint(destination, amount);
}
function permittedBurn(address src, uint256 amount) public {
require(permittedContracts[msg.sender] == 1);
_burn(src, amount);
}
function permittedTransfer(
address src,
address dest,
uint256 amount
) public {
require(permittedContracts[msg.sender] == 1);
_transfer(src, dest, amount);
}
function withdrawBalance(address to, uint256 amount) external onlyOwner {
if (amount == 0) {
amount = address(this).balance;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = payable(to).call{value: amount}("");
require(success, "Transfer failed.");
}
} | burn tokens, allowing sent ETH to be converted according to gweiPerFur | function burnTokens(uint256 amount) private {
if (msg.value > 0 && gweiPerFur > 0) {
uint256 converted = (msg.value * 1 gwei) / gweiPerFur;
if (converted >= amount) {
amount = 0;
amount -= converted;
}
}
if (amount > 0) {
_burn(msg.sender, amount);
}
}
| 14,330,698 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./lib/ReEncryptionValidator.sol";
import "./lib/SignatureVerifier.sol";
import "./StakingEscrow.sol";
import "./proxy/Upgradeable.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/math/Math.sol";
/**
* @title Adjudicator
* @notice Supervises stakers' behavior and punishes when something's wrong.
* @dev |v2.1.2|
*/
contract Adjudicator is Upgradeable {
using SafeMath for uint256;
using UmbralDeserializer for bytes;
event CFragEvaluated(
bytes32 indexed evaluationHash,
address indexed investigator,
bool correctness
);
event IncorrectCFragVerdict(
bytes32 indexed evaluationHash,
address indexed worker,
address indexed staker
);
// used only for upgrading
bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0);
address constant RESERVED_ADDRESS = address(0);
StakingEscrow public immutable escrow;
SignatureVerifier.HashAlgorithm public immutable hashAlgorithm;
uint256 public immutable basePenalty;
uint256 public immutable penaltyHistoryCoefficient;
uint256 public immutable percentagePenaltyCoefficient;
uint256 public immutable rewardCoefficient;
mapping (address => uint256) public penaltyHistory;
mapping (bytes32 => bool) public evaluatedCFrags;
/**
* @param _escrow Escrow contract
* @param _hashAlgorithm Hashing algorithm
* @param _basePenalty Base for the penalty calculation
* @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history
* @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty
* @param _rewardCoefficient Coefficient for calculating the reward
*/
constructor(
StakingEscrow _escrow,
SignatureVerifier.HashAlgorithm _hashAlgorithm,
uint256 _basePenalty,
uint256 _penaltyHistoryCoefficient,
uint256 _percentagePenaltyCoefficient,
uint256 _rewardCoefficient
) {
// Sanity checks.
require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address.
// The reward and penalty coefficients are set.
_percentagePenaltyCoefficient != 0 &&
_rewardCoefficient != 0);
escrow = _escrow;
hashAlgorithm = _hashAlgorithm;
basePenalty = _basePenalty;
percentagePenaltyCoefficient = _percentagePenaltyCoefficient;
penaltyHistoryCoefficient = _penaltyHistoryCoefficient;
rewardCoefficient = _rewardCoefficient;
}
/**
* @notice Submit proof that a worker created wrong CFrag
* @param _capsuleBytes Serialized capsule
* @param _cFragBytes Serialized CFrag
* @param _cFragSignature Signature of CFrag by worker
* @param _taskSignature Signature of task specification by Bob
* @param _requesterPublicKey Bob's signing public key, also known as "stamp"
* @param _workerPublicKey Worker's signing public key, also known as "stamp"
* @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key
* @param _preComputedData Additional pre-computed data for CFrag correctness verification
*/
function evaluateCFrag(
bytes memory _capsuleBytes,
bytes memory _cFragBytes,
bytes memory _cFragSignature,
bytes memory _taskSignature,
bytes memory _requesterPublicKey,
bytes memory _workerPublicKey,
bytes memory _workerIdentityEvidence,
bytes memory _preComputedData
)
public
{
// 1. Check that CFrag is not evaluated yet
bytes32 evaluationHash = SignatureVerifier.hash(
abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm);
require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated.");
evaluatedCFrags[evaluationHash] = true;
// 2. Verify correctness of re-encryption
bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData);
emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect);
// 3. Verify associated public keys and signatures
require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey),
"Staker's public key is invalid");
require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey),
"Requester's public key is invalid");
UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData();
// Verify worker's signature of CFrag
require(SignatureVerifier.verify(
_cFragBytes,
abi.encodePacked(_cFragSignature, precomp.lostBytes[1]),
_workerPublicKey,
hashAlgorithm),
"CFrag signature is invalid"
);
// Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata
UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag();
require(SignatureVerifier.verify(
_taskSignature,
abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]),
_workerPublicKey,
hashAlgorithm),
"Task signature is invalid"
);
// Verify that _taskSignature is bob's signature of the task specification.
// A task specification is: capsule + ursula pubkey + alice address + blockhash
bytes32 stampXCoord;
assembly {
stampXCoord := mload(add(_workerPublicKey, 32))
}
bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord);
require(SignatureVerifier.verify(
abi.encodePacked(_capsuleBytes,
stamp,
_workerIdentityEvidence,
precomp.alicesKeyAsAddress,
bytes32(0)),
abi.encodePacked(_taskSignature, precomp.lostBytes[3]),
_requesterPublicKey,
hashAlgorithm),
"Specification signature is invalid"
);
// 4. Extract worker address from stamp signature.
address worker = SignatureVerifier.recover(
SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures
_workerIdentityEvidence);
address staker = escrow.stakerFromWorker(worker);
require(staker != address(0), "Worker must be related to a staker");
// 5. Check that staker can be slashed
uint256 stakerValue = escrow.getAllTokens(staker);
require(stakerValue > 0, "Staker has no tokens");
// 6. If CFrag was incorrect, slash staker
if (!cFragIsCorrect) {
(uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue);
escrow.slashStaker(staker, penalty, msg.sender, reward);
emit IncorrectCFragVerdict(evaluationHash, worker, staker);
}
}
/**
* @notice Calculate penalty to the staker and reward to the investigator
* @param _staker Staker's address
* @param _stakerValue Amount of tokens that belong to the staker
*/
function calculatePenaltyAndReward(address _staker, uint256 _stakerValue)
internal returns (uint256 penalty, uint256 reward)
{
penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker]));
penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient));
reward = penalty.div(rewardCoefficient);
// TODO add maximum condition or other overflow protection or other penalty condition (#305?)
penaltyHistory[_staker] = penaltyHistory[_staker].add(1);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
bytes32 evaluationCFragHash = SignatureVerifier.hash(
abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256);
require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) ==
(evaluatedCFrags[evaluationCFragHash] ? 1 : 0));
require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) ==
penaltyHistory[RESERVED_ADDRESS]);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// preparation for the verifyState method
bytes32 evaluationCFragHash = SignatureVerifier.hash(
abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256);
evaluatedCFrags[evaluationCFragHash] = true;
penaltyHistory[RESERVED_ADDRESS] = 123;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./UmbralDeserializer.sol";
import "./SignatureVerifier.sol";
/**
* @notice Validates re-encryption correctness.
*/
library ReEncryptionValidator {
using UmbralDeserializer for bytes;
//------------------------------//
// Umbral-specific constants //
//------------------------------//
// See parameter `u` of `UmbralParameters` class in pyUmbral
// https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py
uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02;
uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f;
uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936;
//------------------------------//
// SECP256K1-specific constants //
//------------------------------//
// Base field order
uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// -2 mod FIELD_ORDER
uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d;
// (-1/2) mod FIELD_ORDER
uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17;
//
/**
* @notice Check correctness of re-encryption
* @param _capsuleBytes Capsule
* @param _cFragBytes Capsule frag
* @param _precomputedBytes Additional precomputed data
*/
function validateCFrag(
bytes memory _capsuleBytes,
bytes memory _cFragBytes,
bytes memory _precomputedBytes
)
internal pure returns (bool)
{
UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule();
UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag();
UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData();
// Extract Alice's address and check that it corresponds to the one provided
address alicesAddress = SignatureVerifier.recover(
_precomputed.hashedKFragValidityMessage,
abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0])
);
require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature");
// Compute proof's challenge scalar h, used in all ZKP verification equations
uint256 h = computeProofChallengeScalar(_capsule, _cFrag);
//////
// Verifying 1st equation: z*E == h*E_1 + E_2
//////
// Input validation: E
require(checkCompressedPoint(
_capsule.pointE.sign,
_capsule.pointE.xCoord,
_precomputed.pointEyCoord),
"Precomputed Y coordinate of E doesn't correspond to compressed E point"
);
// Input validation: z*E
require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord),
"Point zE is not a valid EC point"
);
require(ecmulVerify(
_capsule.pointE.xCoord, // E_x
_precomputed.pointEyCoord, // E_y
_cFrag.proof.bnSig, // z
_precomputed.pointEZxCoord, // zE_x
_precomputed.pointEZyCoord), // zE_y
"Precomputed z*E value is incorrect"
);
// Input validation: E1
require(checkCompressedPoint(
_cFrag.pointE1.sign, // E1_sign
_cFrag.pointE1.xCoord, // E1_x
_precomputed.pointE1yCoord), // E1_y
"Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point"
);
// Input validation: h*E1
require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord),
"Point h*E1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointE1.xCoord, // E1_x
_precomputed.pointE1yCoord, // E1_y
h,
_precomputed.pointE1HxCoord, // hE1_x
_precomputed.pointE1HyCoord), // hE1_y
"Precomputed h*E1 value is incorrect"
);
// Input validation: E2
require(checkCompressedPoint(
_cFrag.proof.pointE2.sign, // E2_sign
_cFrag.proof.pointE2.xCoord, // E2_x
_precomputed.pointE2yCoord), // E2_y
"Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point"
);
bool equation_holds = eqAffineJacobian(
[_precomputed.pointEZxCoord, _precomputed.pointEZyCoord],
addAffineJacobian(
[_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord],
[_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord]
)
);
if (!equation_holds){
return false;
}
//////
// Verifying 2nd equation: z*V == h*V_1 + V_2
//////
// Input validation: V
require(checkCompressedPoint(
_capsule.pointV.sign,
_capsule.pointV.xCoord,
_precomputed.pointVyCoord),
"Precomputed Y coordinate of V doesn't correspond to compressed V point"
);
// Input validation: z*V
require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord),
"Point zV is not a valid EC point"
);
require(ecmulVerify(
_capsule.pointV.xCoord, // V_x
_precomputed.pointVyCoord, // V_y
_cFrag.proof.bnSig, // z
_precomputed.pointVZxCoord, // zV_x
_precomputed.pointVZyCoord), // zV_y
"Precomputed z*V value is incorrect"
);
// Input validation: V1
require(checkCompressedPoint(
_cFrag.pointV1.sign, // V1_sign
_cFrag.pointV1.xCoord, // V1_x
_precomputed.pointV1yCoord), // V1_y
"Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point"
);
// Input validation: h*V1
require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord),
"Point h*V1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointV1.xCoord, // V1_x
_precomputed.pointV1yCoord, // V1_y
h,
_precomputed.pointV1HxCoord, // h*V1_x
_precomputed.pointV1HyCoord), // h*V1_y
"Precomputed h*V1 value is incorrect"
);
// Input validation: V2
require(checkCompressedPoint(
_cFrag.proof.pointV2.sign, // V2_sign
_cFrag.proof.pointV2.xCoord, // V2_x
_precomputed.pointV2yCoord), // V2_y
"Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point"
);
equation_holds = eqAffineJacobian(
[_precomputed.pointVZxCoord, _precomputed.pointVZyCoord],
addAffineJacobian(
[_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord],
[_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord]
)
);
if (!equation_holds){
return false;
}
//////
// Verifying 3rd equation: z*U == h*U_1 + U_2
//////
// We don't have to validate U since it's fixed and hard-coded
// Input validation: z*U
require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord),
"Point z*U is not a valid EC point"
);
require(ecmulVerify(
UMBRAL_PARAMETER_U_XCOORD, // U_x
UMBRAL_PARAMETER_U_YCOORD, // U_y
_cFrag.proof.bnSig, // z
_precomputed.pointUZxCoord, // zU_x
_precomputed.pointUZyCoord), // zU_y
"Precomputed z*U value is incorrect"
);
// Input validation: U1 (a.k.a. KFragCommitment)
require(checkCompressedPoint(
_cFrag.proof.pointKFragCommitment.sign, // U1_sign
_cFrag.proof.pointKFragCommitment.xCoord, // U1_x
_precomputed.pointU1yCoord), // U1_y
"Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point"
);
// Input validation: h*U1
require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord),
"Point h*U1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.proof.pointKFragCommitment.xCoord, // U1_x
_precomputed.pointU1yCoord, // U1_y
h,
_precomputed.pointU1HxCoord, // h*V1_x
_precomputed.pointU1HyCoord), // h*V1_y
"Precomputed h*V1 value is incorrect"
);
// Input validation: U2 (a.k.a. KFragPok ("proof of knowledge"))
require(checkCompressedPoint(
_cFrag.proof.pointKFragPok.sign, // U2_sign
_cFrag.proof.pointKFragPok.xCoord, // U2_x
_precomputed.pointU2yCoord), // U2_y
"Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point"
);
equation_holds = eqAffineJacobian(
[_precomputed.pointUZxCoord, _precomputed.pointUZyCoord],
addAffineJacobian(
[_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord],
[_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord]
)
);
return equation_holds;
}
function computeProofChallengeScalar(
UmbralDeserializer.Capsule memory _capsule,
UmbralDeserializer.CapsuleFrag memory _cFrag
) internal pure returns (uint256) {
// Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata)
bytes memory hashInput = abi.encodePacked(
// Point E
_capsule.pointE.sign,
_capsule.pointE.xCoord,
// Point E1
_cFrag.pointE1.sign,
_cFrag.pointE1.xCoord,
// Point E2
_cFrag.proof.pointE2.sign,
_cFrag.proof.pointE2.xCoord
);
hashInput = abi.encodePacked(
hashInput,
// Point V
_capsule.pointV.sign,
_capsule.pointV.xCoord,
// Point V1
_cFrag.pointV1.sign,
_cFrag.pointV1.xCoord,
// Point V2
_cFrag.proof.pointV2.sign,
_cFrag.proof.pointV2.xCoord
);
hashInput = abi.encodePacked(
hashInput,
// Point U
bytes1(UMBRAL_PARAMETER_U_SIGN),
bytes32(UMBRAL_PARAMETER_U_XCOORD),
// Point U1
_cFrag.proof.pointKFragCommitment.sign,
_cFrag.proof.pointKFragCommitment.xCoord,
// Point U2
_cFrag.proof.pointKFragPok.sign,
_cFrag.proof.pointKFragPok.xCoord,
// Re-encryption metadata
_cFrag.proof.metadata
);
uint256 h = extendedKeccakToBN(hashInput);
return h;
}
function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) {
bytes32 upper;
bytes32 lower;
// Umbral prepends to the data a customization string of 64-bytes.
// In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes.
bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data);
(upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)),
keccak256(abi.encodePacked(uint8(0x01), input)));
// Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1)
// n_minus_1 = n - 1
// delta = 2^256 mod n_minus_1
uint256 delta = 0x14551231950b75fc4402da1732fc9bec0;
uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140;
uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1);
return 1 + addmod(upper_half, uint256(lower), n_minus_1);
}
/// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate
/// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise
/// @param _pointX The X coordinate of an EC point in affine representation
/// @param _pointY The Y coordinate of an EC point in affine representation
/// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY)
function checkCompressedPoint(
uint8 _pointSign,
uint256 _pointX,
uint256 _pointY
) internal pure returns(bool) {
bool correct_sign = _pointY % 2 == _pointSign - 2;
return correct_sign && isOnCurve(_pointX, _pointY);
}
/// @notice Tests if the given serialized coordinates represent a valid EC point
/// @param _coords The concatenation of serialized X and Y coordinates
/// @return true iff coordinates X and Y are a valid point
function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) {
require(_coords.length == 64, "Serialized coordinates should be 64 B");
uint256 coordX;
uint256 coordY;
assembly {
coordX := mload(add(_coords, 32))
coordY := mload(add(_coords, 64))
}
return isOnCurve(coordX, coordY);
}
/// @notice Tests if a point is on the secp256k1 curve
/// @param Px The X coordinate of an EC point in affine representation
/// @param Py The Y coordinate of an EC point in affine representation
/// @return true if (Px, Py) is a valid secp256k1 point; false otherwise
function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) {
uint256 p = FIELD_ORDER;
if (Px >= p || Py >= p){
return false;
}
uint256 y2 = mulmod(Py, Py, p);
uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p);
return y2 == x3_plus_7;
}
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4
function ecmulVerify(
uint256 x1,
uint256 y1,
uint256 scalar,
uint256 qx,
uint256 qy
) internal pure returns(bool) {
uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order)));
address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return xyAddress == signer;
}
/// @notice Equality test of two points, in affine and Jacobian coordinates respectively
/// @param P An EC point in affine coordinates
/// @param Q An EC point in Jacobian coordinates
/// @return true if P and Q represent the same point in affine coordinates; false otherwise
function eqAffineJacobian(
uint256[2] memory P,
uint256[3] memory Q
) internal pure returns(bool){
uint256 Qz = Q[2];
if(Qz == 0){
return false; // Q is zero but P isn't.
}
uint256 p = FIELD_ORDER;
uint256 Q_z_squared = mulmod(Qz, Qz, p);
return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1];
}
/// @notice Adds two points in affine coordinates, with the result in Jacobian
/// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3
/// @param P An EC point in affine coordinates
/// @param Q An EC point in affine coordinates
/// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256
function addAffineJacobian(
uint[2] memory P,
uint[2] memory Q
) internal pure returns (uint[3] memory R) {
uint256 p = FIELD_ORDER;
uint256 a = P[0];
uint256 c = P[1];
uint256 t0 = Q[0];
uint256 t1 = Q[1];
if ((a == t0) && (c == t1)){
return doubleJacobian([a, c, 1]);
}
uint256 d = addmod(t1, p-c, p); // d = t1 - c
uint256 b = addmod(t0, p-a, p); // b = t0 - a
uint256 e = mulmod(b, b, p); // e = b^2
uint256 f = mulmod(e, b, p); // f = b^3
uint256 g = mulmod(a, e, p);
R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p);
R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p);
R[2] = b;
}
/// @notice Point doubling in Jacobian coordinates
/// @param P An EC point in Jacobian coordinates.
/// @return Q An EC point in Jacobian coordinates
function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) {
uint256 z = P[2];
if (z == 0)
return Q;
uint256 p = FIELD_ORDER;
uint256 x = P[0];
uint256 _2y = mulmod(2, P[1], p);
uint256 _4yy = mulmod(_2y, _2y, p);
uint256 s = mulmod(_4yy, x, p);
uint256 m = mulmod(3, mulmod(x, x, p), p);
uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p);
Q[0] = t;
Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p);
Q[2] = mulmod(_2y, z, p);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @notice Deserialization library for Umbral objects
*/
library UmbralDeserializer {
struct Point {
uint8 sign;
uint256 xCoord;
}
struct Capsule {
Point pointE;
Point pointV;
uint256 bnSig;
}
struct CorrectnessProof {
Point pointE2;
Point pointV2;
Point pointKFragCommitment;
Point pointKFragPok;
uint256 bnSig;
bytes kFragSignature; // 64 bytes
bytes metadata; // any length
}
struct CapsuleFrag {
Point pointE1;
Point pointV1;
bytes32 kFragId;
Point pointPrecursor;
CorrectnessProof proof;
}
struct PreComputedData {
uint256 pointEyCoord;
uint256 pointEZxCoord;
uint256 pointEZyCoord;
uint256 pointE1yCoord;
uint256 pointE1HxCoord;
uint256 pointE1HyCoord;
uint256 pointE2yCoord;
uint256 pointVyCoord;
uint256 pointVZxCoord;
uint256 pointVZyCoord;
uint256 pointV1yCoord;
uint256 pointV1HxCoord;
uint256 pointV1HyCoord;
uint256 pointV2yCoord;
uint256 pointUZxCoord;
uint256 pointUZyCoord;
uint256 pointU1yCoord;
uint256 pointU1HxCoord;
uint256 pointU1HyCoord;
uint256 pointU2yCoord;
bytes32 hashedKFragValidityMessage;
address alicesKeyAsAddress;
bytes5 lostBytes;
}
uint256 constant BIGNUM_SIZE = 32;
uint256 constant POINT_SIZE = 33;
uint256 constant SIGNATURE_SIZE = 64;
uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE;
uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE;
uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE;
uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE;
uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5;
/**
* @notice Deserialize to capsule (not activated)
*/
function toCapsule(bytes memory _capsuleBytes)
internal pure returns (Capsule memory capsule)
{
require(_capsuleBytes.length == CAPSULE_SIZE);
uint256 pointer = getPointer(_capsuleBytes);
pointer = copyPoint(pointer, capsule.pointE);
pointer = copyPoint(pointer, capsule.pointV);
capsule.bnSig = uint256(getBytes32(pointer));
}
/**
* @notice Deserialize to correctness proof
* @param _pointer Proof bytes memory pointer
* @param _proofBytesLength Proof bytes length
*/
function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength)
internal pure returns (CorrectnessProof memory proof)
{
require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE);
_pointer = copyPoint(_pointer, proof.pointE2);
_pointer = copyPoint(_pointer, proof.pointV2);
_pointer = copyPoint(_pointer, proof.pointKFragCommitment);
_pointer = copyPoint(_pointer, proof.pointKFragPok);
proof.bnSig = uint256(getBytes32(_pointer));
_pointer += BIGNUM_SIZE;
proof.kFragSignature = new bytes(SIGNATURE_SIZE);
// TODO optimize, just two mload->mstore (#1500)
_pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE);
if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) {
proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE);
copyBytes(_pointer, proof.metadata, proof.metadata.length);
}
}
/**
* @notice Deserialize to correctness proof
*/
function toCorrectnessProof(bytes memory _proofBytes)
internal pure returns (CorrectnessProof memory proof)
{
uint256 pointer = getPointer(_proofBytes);
return toCorrectnessProof(pointer, _proofBytes.length);
}
/**
* @notice Deserialize to CapsuleFrag
*/
function toCapsuleFrag(bytes memory _cFragBytes)
internal pure returns (CapsuleFrag memory cFrag)
{
uint256 cFragBytesLength = _cFragBytes.length;
require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE);
uint256 pointer = getPointer(_cFragBytes);
pointer = copyPoint(pointer, cFrag.pointE1);
pointer = copyPoint(pointer, cFrag.pointV1);
cFrag.kFragId = getBytes32(pointer);
pointer += BIGNUM_SIZE;
pointer = copyPoint(pointer, cFrag.pointPrecursor);
cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE);
}
/**
* @notice Deserialize to precomputed data
*/
function toPreComputedData(bytes memory _preComputedData)
internal pure returns (PreComputedData memory data)
{
require(_preComputedData.length == PRECOMPUTED_DATA_SIZE);
uint256 initial_pointer = getPointer(_preComputedData);
uint256 pointer = initial_pointer;
data.pointEyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointEZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointEZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointE2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointVZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointV2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointUZxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointUZyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1HxCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU1HyCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.pointU2yCoord = uint256(getBytes32(pointer));
pointer += BIGNUM_SIZE;
data.hashedKFragValidityMessage = getBytes32(pointer);
pointer += 32;
data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer)));
pointer += 20;
// Lost bytes: a bytes5 variable holding the following byte values:
// 0: kfrag signature recovery value v
// 1: cfrag signature recovery value v
// 2: metadata signature recovery value v
// 3: specification signature recovery value v
// 4: ursula pubkey sign byte
data.lostBytes = bytes5(getBytes32(pointer));
pointer += 5;
require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE);
}
// TODO extract to external library if needed (#1500)
/**
* @notice Get the memory pointer for start of array
*/
function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) {
assembly {
pointer := add(_bytes, 32) // skip array length
}
}
/**
* @notice Copy point data from memory in the pointer position
*/
function copyPoint(uint256 _pointer, Point memory _point)
internal pure returns (uint256 resultPointer)
{
// TODO optimize, copy to point memory directly (#1500)
uint8 temp;
uint256 xCoord;
assembly {
temp := byte(0, mload(_pointer))
xCoord := mload(add(_pointer, 1))
}
_point.sign = temp;
_point.xCoord = xCoord;
resultPointer = _pointer + POINT_SIZE;
}
/**
* @notice Read 1 byte from memory in the pointer position
*/
function getByte(uint256 _pointer) internal pure returns (byte result) {
bytes32 word;
assembly {
word := mload(_pointer)
}
result = word[0];
return result;
}
/**
* @notice Read 32 bytes from memory in the pointer position
*/
function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) {
assembly {
result := mload(_pointer)
}
}
/**
* @notice Copy bytes from the source pointer to the target array
* @dev Assumes that enough memory has been allocated to store in target.
* Also assumes that '_target' was the last thing that was allocated
* @param _bytesPointer Source memory pointer
* @param _target Target array
* @param _bytesLength Number of bytes to copy
*/
function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength)
internal
pure
returns (uint256 resultPointer)
{
// Exploiting the fact that '_target' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
// evm operations on words
let words := div(add(_bytesLength, 31), 32)
let source := _bytesPointer
let destination := add(_target, 32)
for
{ let i := 0 } // start at arr + 32 -> first byte corresponds to length
lt(i, words)
{ i := add(i, 1) }
{
let offset := mul(i, 32)
mstore(add(destination, offset), mload(add(source, offset)))
}
mstore(add(_target, add(32, mload(_target))), 0)
}
resultPointer = _bytesPointer + _bytesLength;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @notice Library to recover address and verify signatures
* @dev Simple wrapper for `ecrecover`
*/
library SignatureVerifier {
enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160}
// Header for Version E as defined by EIP191. First byte ('E') is also the version
bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n";
/**
* @notice Recover signer address from hash and signature
* @param _hash 32 bytes message hash
* @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28)
*/
function recover(bytes32 _hash, bytes memory _signature)
internal
pure
returns (address)
{
require(_signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
return ecrecover(_hash, v, r, s);
}
/**
* @notice Transform public key to address
* @param _publicKey secp256k1 public key
*/
function toAddress(bytes memory _publicKey) internal pure returns (address) {
return address(uint160(uint256(keccak256(_publicKey))));
}
/**
* @notice Hash using one of pre built hashing algorithm
* @param _message Signed message
* @param _algorithm Hashing algorithm
*/
function hash(bytes memory _message, HashAlgorithm _algorithm)
internal
pure
returns (bytes32 result)
{
if (_algorithm == HashAlgorithm.KECCAK256) {
result = keccak256(_message);
} else if (_algorithm == HashAlgorithm.SHA256) {
result = sha256(_message);
} else {
result = ripemd160(_message);
}
}
/**
* @notice Verify ECDSA signature
* @dev Uses one of pre built hashing algorithm
* @param _message Signed message
* @param _signature Signature of message hash
* @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes)
* @param _algorithm Hashing algorithm
*/
function verify(
bytes memory _message,
bytes memory _signature,
bytes memory _publicKey,
HashAlgorithm _algorithm
)
internal
pure
returns (bool)
{
require(_publicKey.length == 64);
return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature);
}
/**
* @notice Hash message according to EIP191 signature specification
* @dev It always assumes Keccak256 is used as hashing algorithm
* @dev Only supports version 0 and version E (0x45)
* @param _message Message to sign
* @param _version EIP191 version to use
*/
function hashEIP191(
bytes memory _message,
byte _version
)
internal
view
returns (bytes32 result)
{
if(_version == byte(0x00)){ // Version 0: Data with intended validator
address validator = address(this);
return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message));
} else if (_version == byte(0x45)){ // Version E: personal_sign messages
uint256 length = _message.length;
require(length > 0, "Empty message not allowed for version E");
// Compute text-encoded length of message
uint256 digits = 0;
while (length != 0) {
digits++;
length /= 10;
}
bytes memory lengthAsText = new bytes(digits);
length = _message.length;
uint256 index = digits - 1;
while (length != 0) {
lengthAsText[index--] = byte(uint8(48 + length % 10));
length /= 10;
}
return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message));
} else {
revert("Unsupported EIP191 version");
}
}
/**
* @notice Verify EIP191 signature
* @dev It always assumes Keccak256 is used as hashing algorithm
* @dev Only supports version 0 and version E (0x45)
* @param _message Signed message
* @param _signature Signature of message hash
* @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes)
* @param _version EIP191 version to use
*/
function verifyEIP191(
bytes memory _message,
bytes memory _signature,
bytes memory _publicKey,
byte _version
)
internal
view
returns (bool)
{
require(_publicKey.length == 64);
return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../aragon/interfaces/IERC900History.sol";
import "./Issuer.sol";
import "./lib/Bits.sol";
import "./lib/Snapshot.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
/**
* @notice PolicyManager interface
*/
interface PolicyManagerInterface {
function secondsPerPeriod() external view returns (uint32);
function register(address _node, uint16 _period) external;
function migrate(address _node) external;
function ping(
address _node,
uint16 _processedPeriod1,
uint16 _processedPeriod2,
uint16 _periodToSetDefault
) external;
}
/**
* @notice Adjudicator interface
*/
interface AdjudicatorInterface {
function rewardCoefficient() external view returns (uint32);
}
/**
* @notice WorkLock interface
*/
interface WorkLockInterface {
function token() external view returns (NuCypherToken);
}
/**
* @title StakingEscrowStub
* @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable
* @dev |v1.0.0|
*/
contract StakingEscrowStub is Upgradeable {
using AdditionalMath for uint32;
NuCypherToken public immutable token;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
uint16 public immutable minLockedPeriods;
uint256 public immutable minAllowableLockedTokens;
uint256 public immutable maxAllowableLockedTokens;
/**
* @notice Predefines some variables for use when deploying other contracts
* @param _token Token contract
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
*/
constructor(
NuCypherToken _token,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens
) {
require(_token.totalSupply() > 0 &&
_hoursPerPeriod != 0 &&
_genesisHoursPerPeriod != 0 &&
_genesisHoursPerPeriod <= _hoursPerPeriod &&
_minLockedPeriods > 1 &&
_maxAllowableLockedTokens != 0);
token = _token;
secondsPerPeriod = _hoursPerPeriod.mul32(1 hours);
genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
// we have to use real values even though this is a stub
require(address(delegateGet(_testTarget, this.token.selector)) == address(token));
// TODO uncomment after merging this PR #2579
// require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod);
require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod);
require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods);
require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens);
require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens);
}
}
/**
* @title StakingEscrow
* @notice Contract holds and locks stakers tokens.
* Each staker that locks their tokens will receive some compensation
* @dev |v5.7.1|
*/
contract StakingEscrow is Issuer, IERC900History {
using AdditionalMath for uint256;
using AdditionalMath for uint16;
using Bits for uint256;
using SafeMath for uint256;
using Snapshot for uint128[];
using SafeERC20 for NuCypherToken;
/**
* @notice Signals that tokens were deposited
* @param staker Staker address
* @param value Amount deposited (in NuNits)
* @param periods Number of periods tokens will be locked
*/
event Deposited(address indexed staker, uint256 value, uint16 periods);
/**
* @notice Signals that tokens were stake locked
* @param staker Staker address
* @param value Amount locked (in NuNits)
* @param firstPeriod Starting lock period
* @param periods Number of periods tokens will be locked
*/
event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods);
/**
* @notice Signals that a sub-stake was divided
* @param staker Staker address
* @param oldValue Old sub-stake value (in NuNits)
* @param lastPeriod Final locked period of old sub-stake
* @param newValue New sub-stake value (in NuNits)
* @param periods Number of periods to extend sub-stake
*/
event Divided(
address indexed staker,
uint256 oldValue,
uint16 lastPeriod,
uint256 newValue,
uint16 periods
);
/**
* @notice Signals that two sub-stakes were merged
* @param staker Staker address
* @param value1 Value of first sub-stake (in NuNits)
* @param value2 Value of second sub-stake (in NuNits)
* @param lastPeriod Final locked period of merged sub-stake
*/
event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod);
/**
* @notice Signals that a sub-stake was prolonged
* @param staker Staker address
* @param value Value of sub-stake
* @param lastPeriod Final locked period of old sub-stake
* @param periods Number of periods sub-stake was extended
*/
event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods);
/**
* @notice Signals that tokens were withdrawn to the staker
* @param staker Staker address
* @param value Amount withdraws (in NuNits)
*/
event Withdrawn(address indexed staker, uint256 value);
/**
* @notice Signals that the worker associated with the staker made a commitment to next period
* @param staker Staker address
* @param period Period committed to
* @param value Amount of tokens staked for the committed period
*/
event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value);
/**
* @notice Signals that tokens were minted for previous periods
* @param staker Staker address
* @param period Previous period tokens minted for
* @param value Amount minted (in NuNits)
*/
event Minted(address indexed staker, uint16 indexed period, uint256 value);
/**
* @notice Signals that the staker was slashed
* @param staker Staker address
* @param penalty Slashing penalty
* @param investigator Investigator address
* @param reward Value of reward provided to investigator (in NuNits)
*/
event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward);
/**
* @notice Signals that the restake parameter was activated/deactivated
* @param staker Staker address
* @param reStake Updated parameter value
*/
event ReStakeSet(address indexed staker, bool reStake);
/**
* @notice Signals that a worker was bonded to the staker
* @param staker Staker address
* @param worker Worker address
* @param startPeriod Period bonding occurred
*/
event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod);
/**
* @notice Signals that the winddown parameter was activated/deactivated
* @param staker Staker address
* @param windDown Updated parameter value
*/
event WindDownSet(address indexed staker, bool windDown);
/**
* @notice Signals that the snapshot parameter was activated/deactivated
* @param staker Staker address
* @param snapshotsEnabled Updated parameter value
*/
event SnapshotSet(address indexed staker, bool snapshotsEnabled);
/**
* @notice Signals that the staker migrated their stake to the new period length
* @param staker Staker address
* @param period Period when migration happened
*/
event Migrated(address indexed staker, uint16 indexed period);
/// internal event
event WorkMeasurementSet(address indexed staker, bool measureWork);
struct SubStakeInfo {
uint16 firstPeriod;
uint16 lastPeriod;
uint16 unlockingDuration;
uint128 lockedValue;
}
struct Downtime {
uint16 startPeriod;
uint16 endPeriod;
}
struct StakerInfo {
uint256 value;
/*
* Stores periods that are committed but not yet rewarded.
* In order to optimize storage, only two values are used instead of an array.
* commitToNextPeriod() method invokes mint() method so there can only be two committed
* periods that are not yet rewarded: the current and the next periods.
*/
uint16 currentCommittedPeriod;
uint16 nextCommittedPeriod;
uint16 lastCommittedPeriod;
uint16 stub1; // former slot for lockReStakeUntilPeriod
uint256 completedWork;
uint16 workerStartPeriod; // period when worker was bonded
address worker;
uint256 flags; // uint256 to acquire whole slot and minimize operations on it
uint256 reservedSlot1;
uint256 reservedSlot2;
uint256 reservedSlot3;
uint256 reservedSlot4;
uint256 reservedSlot5;
Downtime[] pastDowntime;
SubStakeInfo[] subStakes;
uint128[] history;
}
// used only for upgrading
uint16 internal constant RESERVED_PERIOD = 0;
uint16 internal constant MAX_CHECKED_VALUES = 5;
// to prevent high gas consumption in loops for slashing
uint16 public constant MAX_SUB_STAKES = 30;
uint16 internal constant MAX_UINT16 = 65535;
// indices for flags
uint8 internal constant RE_STAKE_DISABLED_INDEX = 0;
uint8 internal constant WIND_DOWN_INDEX = 1;
uint8 internal constant MEASURE_WORK_INDEX = 2;
uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3;
uint8 internal constant MIGRATED_INDEX = 4;
uint16 public immutable minLockedPeriods;
uint16 public immutable minWorkerPeriods;
uint256 public immutable minAllowableLockedTokens;
uint256 public immutable maxAllowableLockedTokens;
PolicyManagerInterface public immutable policyManager;
AdjudicatorInterface public immutable adjudicator;
WorkLockInterface public immutable workLock;
mapping (address => StakerInfo) public stakerInfo;
address[] public stakers;
mapping (address => address) public stakerFromWorker;
mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod
uint128[] public balanceHistory;
address stub1; // former slot for PolicyManager
address stub2; // former slot for Adjudicator
address stub3; // former slot for WorkLock
mapping (uint16 => uint256) _lockedPerPeriod;
// only to make verifyState from previous version work, temporary
// TODO remove after upgrade #2579
function lockedPerPeriod(uint16 _period) public view returns (uint256) {
return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111;
}
/**
* @notice Constructor sets address of token contract and coefficients for minting
* @param _token Token contract
* @param _policyManager Policy Manager contract
* @param _adjudicator Adjudicator contract
* @param _workLock WorkLock contract. Zero address if there is no WorkLock
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays,
* only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2.
* See Equation 10 in Staking Protocol & Economics paper
* @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier)
* where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration
* no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _firstPhaseTotalSupply Total supply for the first phase
* @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1.
* See Equation 7 in Staking Protocol & Economics paper.
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
* @param _minWorkerPeriods Min amount of periods while a worker can't be changed
*/
constructor(
NuCypherToken _token,
PolicyManagerInterface _policyManager,
AdjudicatorInterface _adjudicator,
WorkLockInterface _workLock,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint256 _issuanceDecayCoefficient,
uint256 _lockDurationCoefficient1,
uint256 _lockDurationCoefficient2,
uint16 _maximumRewardedPeriods,
uint256 _firstPhaseTotalSupply,
uint256 _firstPhaseMaxIssuance,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens,
uint16 _minWorkerPeriods
)
Issuer(
_token,
_genesisHoursPerPeriod,
_hoursPerPeriod,
_issuanceDecayCoefficient,
_lockDurationCoefficient1,
_lockDurationCoefficient2,
_maximumRewardedPeriods,
_firstPhaseTotalSupply,
_firstPhaseMaxIssuance
)
{
// constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method
require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
minWorkerPeriods = _minWorkerPeriods;
require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) ||
_policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) &&
_adjudicator.rewardCoefficient() != 0 &&
(address(_workLock) == address(0) || _workLock.token() == _token));
policyManager = _policyManager;
adjudicator = _adjudicator;
workLock = _workLock;
}
/**
* @dev Checks the existence of a staker in the contract
*/
modifier onlyStaker()
{
StakerInfo storage info = stakerInfo[msg.sender];
require((info.value > 0 || info.nextCommittedPeriod != 0) &&
info.flags.bitSet(MIGRATED_INDEX));
_;
}
//------------------------Main getters------------------------
/**
* @notice Get all tokens belonging to the staker
*/
function getAllTokens(address _staker) external view returns (uint256) {
return stakerInfo[_staker].value;
}
/**
* @notice Get all flags for the staker
*/
function getFlags(address _staker)
external view returns (
bool windDown,
bool reStake,
bool measureWork,
bool snapshots,
bool migrated
)
{
StakerInfo storage info = stakerInfo[_staker];
windDown = info.flags.bitSet(WIND_DOWN_INDEX);
reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX);
measureWork = info.flags.bitSet(MEASURE_WORK_INDEX);
snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX);
migrated = info.flags.bitSet(MIGRATED_INDEX);
}
/**
* @notice Get the start period. Use in the calculation of the last period of the sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
*/
function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod)
internal view returns (uint16)
{
// if the next period (after current) is committed
if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) {
return _currentPeriod + 1;
}
return _currentPeriod;
}
/**
* @notice Get the last period of the sub stake
* @param _subStake Sub stake structure
* @param _startPeriod Pre-calculated start period
*/
function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod)
internal view returns (uint16)
{
if (_subStake.lastPeriod != 0) {
return _subStake.lastPeriod;
}
uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration;
if (lastPeriod > uint32(MAX_UINT16)) {
return MAX_UINT16;
}
return uint16(lastPeriod);
}
/**
* @notice Get the last period of the sub stake
* @param _staker Staker
* @param _index Stake index
*/
function getLastPeriodOfSubStake(address _staker, uint256 _index)
public view returns (uint16)
{
StakerInfo storage info = stakerInfo[_staker];
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 startPeriod = getStartPeriod(info, getCurrentPeriod());
return getLastPeriodOfSubStake(subStake, startPeriod);
}
/**
* @notice Get the value of locked tokens for a staker in a specified period
* @dev Information may be incorrect for rewarded or not committed surpassed period
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _period Next period
*/
function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period)
internal view returns (uint256 lockedValue)
{
lockedValue = 0;
uint16 startPeriod = getStartPeriod(_info, _currentPeriod);
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.firstPeriod <= _period &&
getLastPeriodOfSubStake(subStake, startPeriod) >= _period) {
lockedValue += subStake.lockedValue;
}
}
}
/**
* @notice Get the value of locked tokens for a staker in a future period
* @dev This function is used by PreallocationEscrow so its signature can't be updated.
* @param _staker Staker
* @param _offsetPeriods Amount of periods that will be added to the current period
*/
function getLockedTokens(address _staker, uint16 _offsetPeriods)
external view returns (uint256 lockedValue)
{
StakerInfo storage info = stakerInfo[_staker];
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(_offsetPeriods);
return getLockedTokens(info, currentPeriod, nextPeriod);
}
/**
* @notice Get the last committed staker's period
* @param _staker Staker
*/
function getLastCommittedPeriod(address _staker) public view returns (uint16) {
StakerInfo storage info = stakerInfo[_staker];
return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod;
}
/**
* @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period
* as well as stakers and their locked tokens
* @param _offsetPeriods Amount of periods for locked tokens calculation
* @param _startIndex Start index for looking in stakers array
* @param _maxStakers Max stakers for looking, if set 0 then all will be used
* @return allLockedTokens Sum of locked tokens for active stakers
* @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256
* @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly!
*/
function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers)
external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers)
{
require(_offsetPeriods > 0);
uint256 endIndex = stakers.length;
require(_startIndex < endIndex);
if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) {
endIndex = _startIndex + _maxStakers;
}
activeStakers = new uint256[2][](endIndex - _startIndex);
allLockedTokens = 0;
uint256 resultIndex = 0;
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(_offsetPeriods);
for (uint256 i = _startIndex; i < endIndex; i++) {
address staker = stakers[i];
StakerInfo storage info = stakerInfo[staker];
if (info.currentCommittedPeriod != currentPeriod &&
info.nextCommittedPeriod != currentPeriod) {
continue;
}
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
if (lockedTokens != 0) {
activeStakers[resultIndex][0] = uint256(staker);
activeStakers[resultIndex++][1] = lockedTokens;
allLockedTokens += lockedTokens;
}
}
assembly {
mstore(activeStakers, resultIndex)
}
}
/**
* @notice Get worker using staker's address
*/
function getWorkerFromStaker(address _staker) external view returns (address) {
return stakerInfo[_staker].worker;
}
/**
* @notice Get work that completed by the staker
*/
function getCompletedWork(address _staker) external view returns (uint256) {
return stakerInfo[_staker].completedWork;
}
/**
* @notice Find index of downtime structure that includes specified period
* @dev If specified period is outside all downtime periods, the length of the array will be returned
* @param _staker Staker
* @param _period Specified period number
*/
function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) {
StakerInfo storage info = stakerInfo[_staker];
for (index = 0; index < info.pastDowntime.length; index++) {
if (_period <= info.pastDowntime[index].endPeriod) {
return index;
}
}
}
//------------------------Main methods------------------------
/**
* @notice Start or stop measuring the work of a staker
* @param _staker Staker
* @param _measureWork Value for `measureWork` parameter
* @return Work that was previously done
*/
function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) {
require(msg.sender == address(workLock));
StakerInfo storage info = stakerInfo[_staker];
if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) {
return info.completedWork;
}
info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX);
emit WorkMeasurementSet(_staker, _measureWork);
return info.completedWork;
}
/**
* @notice Bond worker
* @param _worker Worker address. Must be a real address, not a contract
*/
function bondWorker(address _worker) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
// Specified worker is already bonded with this staker
require(_worker != info.worker);
uint16 currentPeriod = getCurrentPeriod();
if (info.worker != address(0)) { // If this staker had a worker ...
// Check that enough time has passed to change it
require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods));
// Remove the old relation "worker->staker"
stakerFromWorker[info.worker] = address(0);
}
if (_worker != address(0)) {
// Specified worker is already in use
require(stakerFromWorker[_worker] == address(0));
// Specified worker is a staker
require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender);
// Set new worker->staker relation
stakerFromWorker[_worker] = msg.sender;
}
// Bond new worker (or unbond if _worker == address(0))
info.worker = _worker;
info.workerStartPeriod = currentPeriod;
emit WorkerBonded(msg.sender, _worker, currentPeriod);
}
/**
* @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake
* @param _reStake Value for parameter
*/
function setReStake(bool _reStake) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) {
return;
}
info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX);
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Deposit tokens from WorkLock contract
* @param _staker Staker address
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function depositFromWorkLock(
address _staker,
uint256 _value,
uint16 _unlockingDuration
)
external
{
require(msg.sender == address(workLock));
StakerInfo storage info = stakerInfo[_staker];
if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) {
info.flags = info.flags.toggleBit(WIND_DOWN_INDEX);
emit WindDownSet(_staker, true);
}
// WorkLock still uses the genesis period length (24h)
_unlockingDuration = recalculatePeriod(_unlockingDuration);
deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Set `windDown` parameter.
* If true then stake's duration will be decreasing in each period with `commitToNextPeriod()`
* @param _windDown Value for parameter
*/
function setWindDown(bool _windDown) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) {
return;
}
info.flags = info.flags.toggleBit(WIND_DOWN_INDEX);
emit WindDownSet(msg.sender, _windDown);
// duration adjustment if next period is committed
uint16 nextPeriod = getCurrentPeriod() + 1;
if (info.nextCommittedPeriod != nextPeriod) {
return;
}
// adjust sub-stakes duration for the new value of winding down parameter
for (uint256 index = 0; index < info.subStakes.length; index++) {
SubStakeInfo storage subStake = info.subStakes[index];
// sub-stake does not have fixed last period when winding down is disabled
if (!_windDown && subStake.lastPeriod == nextPeriod) {
subStake.lastPeriod = 0;
subStake.unlockingDuration = 1;
continue;
}
// this sub-stake is no longer affected by winding down parameter
if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) {
continue;
}
subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = nextPeriod;
}
}
}
/**
* @notice Activate/deactivate taking snapshots of balances
* @param _enableSnapshots True to activate snapshots, False to deactivate
*/
function setSnapshots(bool _enableSnapshots) external {
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) {
return;
}
uint256 lastGlobalBalance = uint256(balanceHistory.lastValue());
if(_enableSnapshots){
info.history.addSnapshot(info.value);
balanceHistory.addSnapshot(lastGlobalBalance + info.value);
} else {
info.history.addSnapshot(0);
balanceHistory.addSnapshot(lastGlobalBalance - info.value);
}
info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX);
emit SnapshotSet(msg.sender, _enableSnapshots);
}
/**
* @notice Adds a new snapshot to both the staker and global balance histories,
* assuming the staker's balance was already changed
* @param _info Reference to affected staker's struct
* @param _addition Variance in balance. It can be positive or negative.
*/
function addSnapshot(StakerInfo storage _info, int256 _addition) internal {
if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){
_info.history.addSnapshot(_info.value);
uint256 lastGlobalBalance = uint256(balanceHistory.lastValue());
balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition));
}
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Deposit all tokens that were approved to transfer
* @param _from Staker
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes calldata /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// Copy first 32 bytes from _extraData, according to calldata memory layout:
//
// 0x00: method signature 4 bytes
// 0x04: _from 32 bytes after encoding
// 0x24: _value 32 bytes after encoding
// 0x44: _tokenContract 32 bytes after encoding
// 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter)
// 0x84: _extraData length 32 bytes
// 0xA4: _extraData data Length determined by previous variable
//
// See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload));
}
/**
* @notice Deposit tokens and create new sub-stake. Use this method to become a staker
* @param _staker Staker
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external {
deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Deposit tokens and increase lock amount of an existing sub-stake
* @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result
* @param _index Index of the sub stake
* @param _value Amount of tokens which will be locked
*/
function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker {
require(_index < MAX_SUB_STAKES);
deposit(msg.sender, msg.sender, _index, _value, 0);
}
/**
* @notice Deposit tokens
* @dev Specify either index and zero periods (for an existing sub-stake)
* or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both
* @param _staker Staker
* @param _payer Owner of tokens
* @param _index Index of the sub stake
* @param _value Amount of tokens to deposit
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal {
require(_value != 0);
StakerInfo storage info = stakerInfo[_staker];
// A staker can't be a worker for another staker
require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker);
// initial stake of the staker
if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) {
stakers.push(_staker);
policyManager.register(_staker, getCurrentPeriod() - 1);
info.flags = info.flags.toggleBit(MIGRATED_INDEX);
}
require(info.flags.bitSet(MIGRATED_INDEX));
token.safeTransferFrom(_payer, address(this), _value);
info.value += _value;
lock(_staker, _index, _value, _unlockingDuration);
addSnapshot(info, int256(_value));
if (_index >= MAX_SUB_STAKES) {
emit Deposited(_staker, _value, _unlockingDuration);
} else {
uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index);
emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod());
}
}
/**
* @notice Lock some tokens as a new sub-stake
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker {
lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration);
}
/**
* @notice Increase lock amount of an existing sub-stake
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker {
require(_index < MAX_SUB_STAKES);
lock(msg.sender, _index, _value, 0);
}
/**
* @notice Lock some tokens as a stake
* @dev Specify either index and zero periods (for an existing sub-stake)
* or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both
* @param _staker Staker
* @param _index Index of the sub stake
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal {
if (_index < MAX_SUB_STAKES) {
require(_value > 0);
} else {
require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods);
}
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
StakerInfo storage info = stakerInfo[_staker];
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
uint256 requestedLockedTokens = _value.add(lockedTokens);
require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens);
// next period is committed
if (info.nextCommittedPeriod == nextPeriod) {
_lockedPerPeriod[nextPeriod] += _value;
emit CommitmentMade(_staker, nextPeriod, _value);
}
// if index was provided then increase existing sub-stake
if (_index < MAX_SUB_STAKES) {
lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value);
// otherwise create new
} else {
lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration);
}
}
/**
* @notice Lock some tokens as a new sub-stake
* @param _info Staker structure
* @param _nextPeriod Next period
* @param _staker Staker
* @param _value Amount of tokens which will be locked
* @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled
*/
function lockAndCreate(
StakerInfo storage _info,
uint16 _nextPeriod,
address _staker,
uint256 _value,
uint16 _unlockingDuration
)
internal
{
uint16 duration = _unlockingDuration;
// if winding down is enabled and next period is committed
// then sub-stakes duration were decreased
if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) {
duration -= 1;
}
saveSubStake(_info, _nextPeriod, 0, duration, _value);
emit Locked(_staker, _value, _nextPeriod, _unlockingDuration);
}
/**
* @notice Increase lock amount of an existing sub-stake
* @dev Probably will be created a new sub-stake but it will be active only one period
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _nextPeriod Next period
* @param _staker Staker
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _nextPeriod,
address _staker,
uint256 _index,
uint256 _value
)
internal
{
SubStakeInfo storage subStake = _info.subStakes[_index];
(, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod);
// create temporary sub-stake for current or previous committed periods
// to leave locked amount in this period unchanged
if (_info.currentCommittedPeriod != 0 &&
_info.currentCommittedPeriod <= _currentPeriod ||
_info.nextCommittedPeriod != 0 &&
_info.nextCommittedPeriod <= _currentPeriod)
{
saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue);
}
subStake.lockedValue += uint128(_value);
// all new locks should start from the next period
subStake.firstPeriod = _nextPeriod;
emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod);
}
/**
* @notice Checks that last period of sub-stake is greater than the current period
* @param _info Staker structure
* @param _subStake Sub-stake structure
* @param _currentPeriod Current period
* @return startPeriod Start period. Use in the calculation of the last period of the sub stake
* @return lastPeriod Last period of the sub stake
*/
function checkLastPeriodOfSubStake(
StakerInfo storage _info,
SubStakeInfo storage _subStake,
uint16 _currentPeriod
)
internal view returns (uint16 startPeriod, uint16 lastPeriod)
{
startPeriod = getStartPeriod(_info, _currentPeriod);
lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod);
// The sub stake must be active at least in the next period
require(lastPeriod > _currentPeriod);
}
/**
* @notice Save sub stake. First tries to override inactive sub stake
* @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded
* @param _info Staker structure
* @param _firstPeriod First period of the sub stake
* @param _lastPeriod Last period of the sub stake
* @param _unlockingDuration Duration of the sub stake in periods
* @param _lockedValue Amount of locked tokens
*/
function saveSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint16 _lastPeriod,
uint16 _unlockingDuration,
uint256 _lockedValue
)
internal
{
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.lastPeriod != 0 &&
(_info.currentCommittedPeriod == 0 ||
subStake.lastPeriod < _info.currentCommittedPeriod) &&
(_info.nextCommittedPeriod == 0 ||
subStake.lastPeriod < _info.nextCommittedPeriod))
{
subStake.firstPeriod = _firstPeriod;
subStake.lastPeriod = _lastPeriod;
subStake.unlockingDuration = _unlockingDuration;
subStake.lockedValue = uint128(_lockedValue);
return;
}
}
require(_info.subStakes.length < MAX_SUB_STAKES);
_info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue)));
}
/**
* @notice Divide sub stake into two parts
* @param _index Index of the sub stake
* @param _newValue New sub stake value
* @param _additionalDuration Amount of periods for extending sub stake
*/
function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0);
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 currentPeriod = getCurrentPeriod();
(, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod);
uint256 oldValue = subStake.lockedValue;
subStake.lockedValue = uint128(oldValue.sub(_newValue));
require(subStake.lockedValue >= minAllowableLockedTokens);
uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration);
saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue);
emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration);
emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods);
}
/**
* @notice Prolong active sub stake
* @param _index Index of the sub stake
* @param _additionalDuration Amount of periods for extending sub stake
*/
function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
// Incorrect parameters
require(_additionalDuration > 0);
SubStakeInfo storage subStake = info.subStakes[_index];
uint16 currentPeriod = getCurrentPeriod();
(uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod);
subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration);
// if the sub stake ends in the next committed period then reset the `lastPeriod` field
if (lastPeriod == startPeriod) {
subStake.lastPeriod = 0;
}
// The extended sub stake must not be less than the minimum value
require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods);
emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration);
emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration);
}
/**
* @notice Merge two sub-stakes into one if their last periods are equal
* @dev It's possible that both sub-stakes will be active after this transaction.
* But only one of them will be active until next call `commitToNextPeriod` (in the next period)
* @param _index1 Index of the first sub-stake
* @param _index2 Index of the second sub-stake
*/
function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker {
require(_index1 != _index2); // must be different sub-stakes
StakerInfo storage info = stakerInfo[msg.sender];
SubStakeInfo storage subStake1 = info.subStakes[_index1];
SubStakeInfo storage subStake2 = info.subStakes[_index2];
uint16 currentPeriod = getCurrentPeriod();
(, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod);
(, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod);
// both sub-stakes must have equal last period to be mergeable
require(lastPeriod1 == lastPeriod2);
emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1);
if (subStake1.firstPeriod == subStake2.firstPeriod) {
subStake1.lockedValue += subStake2.lockedValue;
subStake2.lastPeriod = 1;
subStake2.unlockingDuration = 0;
} else if (subStake1.firstPeriod > subStake2.firstPeriod) {
subStake1.lockedValue += subStake2.lockedValue;
subStake2.lastPeriod = subStake1.firstPeriod - 1;
subStake2.unlockingDuration = 0;
} else {
subStake2.lockedValue += subStake1.lockedValue;
subStake1.lastPeriod = subStake2.firstPeriod - 1;
subStake1.unlockingDuration = 0;
}
}
/**
* @notice Remove unused sub-stake to decrease gas cost for several methods
*/
function removeUnusedSubStake(uint16 _index) external onlyStaker {
StakerInfo storage info = stakerInfo[msg.sender];
uint256 lastIndex = info.subStakes.length - 1;
SubStakeInfo storage subStake = info.subStakes[_index];
require(subStake.lastPeriod != 0 &&
(info.currentCommittedPeriod == 0 ||
subStake.lastPeriod < info.currentCommittedPeriod) &&
(info.nextCommittedPeriod == 0 ||
subStake.lastPeriod < info.nextCommittedPeriod));
if (_index != lastIndex) {
SubStakeInfo storage lastSubStake = info.subStakes[lastIndex];
subStake.firstPeriod = lastSubStake.firstPeriod;
subStake.lastPeriod = lastSubStake.lastPeriod;
subStake.unlockingDuration = lastSubStake.unlockingDuration;
subStake.lockedValue = lastSubStake.lockedValue;
}
info.subStakes.pop();
}
/**
* @notice Withdraw available amount of tokens to staker
* @param _value Amount of tokens to withdraw
*/
function withdraw(uint256 _value) external onlyStaker {
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
StakerInfo storage info = stakerInfo[msg.sender];
// the max locked tokens in most cases will be in the current period
// but when the staker locks more then we should use the next period
uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod),
getLockedTokens(info, currentPeriod, currentPeriod));
require(_value <= info.value.sub(lockedTokens));
info.value -= _value;
addSnapshot(info, - int256(_value));
token.safeTransfer(msg.sender, _value);
emit Withdrawn(msg.sender, _value);
// unbond worker if staker withdraws last portion of NU
if (info.value == 0 &&
info.nextCommittedPeriod == 0 &&
info.worker != address(0))
{
stakerFromWorker[info.worker] = address(0);
info.worker = address(0);
emit WorkerBonded(msg.sender, address(0), currentPeriod);
}
}
/**
* @notice Make a commitment to the next period and mint for the previous period
*/
function commitToNextPeriod() external isInitialized {
address staker = stakerFromWorker[msg.sender];
StakerInfo storage info = stakerInfo[staker];
// Staker must have a stake to make a commitment
require(info.value > 0);
// Only worker with real address can make a commitment
require(msg.sender == tx.origin);
migrate(staker);
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
// the period has already been committed
require(info.nextCommittedPeriod != nextPeriod);
uint16 lastCommittedPeriod = getLastCommittedPeriod(staker);
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker);
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
require(lockedTokens > 0);
_lockedPerPeriod[nextPeriod] += lockedTokens;
info.currentCommittedPeriod = info.nextCommittedPeriod;
info.nextCommittedPeriod = nextPeriod;
decreaseSubStakesDuration(info, nextPeriod);
// staker was inactive for several periods
if (lastCommittedPeriod < currentPeriod) {
info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod));
}
policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod);
emit CommitmentMade(staker, nextPeriod, lockedTokens);
}
/**
* @notice Migrate from the old period length to the new one. Can be done only once
* @param _staker Staker
*/
function migrate(address _staker) public {
StakerInfo storage info = stakerInfo[_staker];
// check that provided address is/was a staker
require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0);
if (info.flags.bitSet(MIGRATED_INDEX)) {
return;
}
// reset state
info.currentCommittedPeriod = 0;
info.nextCommittedPeriod = 0;
// maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit
info.lastCommittedPeriod = 1;
info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod);
delete info.pastDowntime;
// recalculate all sub-stakes
uint16 currentPeriod = getCurrentPeriod();
for (uint256 i = 0; i < info.subStakes.length; i++) {
SubStakeInfo storage subStake = info.subStakes[i];
subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod);
// sub-stake has fixed last period
if (subStake.lastPeriod != 0) {
subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod);
if (subStake.lastPeriod == 0) {
subStake.lastPeriod = 1;
}
subStake.unlockingDuration = 0;
// sub-stake has no fixed ending but possible that with new period length will have
} else {
uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod);
uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration);
subStake.unlockingDuration = lastPeriod - currentPeriod;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = lastPeriod;
}
}
}
policyManager.migrate(_staker);
info.flags = info.flags.toggleBit(MIGRATED_INDEX);
emit Migrated(_staker, currentPeriod);
}
/**
* @notice Decrease sub-stakes duration if `windDown` is enabled
*/
function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal {
if (!_info.flags.bitSet(WIND_DOWN_INDEX)) {
return;
}
for (uint256 index = 0; index < _info.subStakes.length; index++) {
SubStakeInfo storage subStake = _info.subStakes[index];
if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) {
continue;
}
subStake.unlockingDuration--;
if (subStake.unlockingDuration == 0) {
subStake.lastPeriod = _nextPeriod;
}
}
}
/**
* @notice Mint tokens for previous periods if staker locked their tokens and made a commitment
*/
function mint() external onlyStaker {
// save last committed period to the storage if both periods will be empty after minting
// because we won't be able to calculate last committed period
// see getLastCommittedPeriod(address)
StakerInfo storage info = stakerInfo[msg.sender];
uint16 previousPeriod = getCurrentPeriod() - 1;
if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) {
info.lastCommittedPeriod = info.nextCommittedPeriod;
}
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender);
if (processedPeriod1 != 0 || processedPeriod2 != 0) {
policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0);
}
}
/**
* @notice Mint tokens for previous periods if staker locked their tokens and made a commitment
* @param _staker Staker
* @return processedPeriod1 Processed period: currentCommittedPeriod or zero
* @return processedPeriod2 Processed period: nextCommittedPeriod or zero
*/
function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) {
uint16 currentPeriod = getCurrentPeriod();
uint16 previousPeriod = currentPeriod - 1;
StakerInfo storage info = stakerInfo[_staker];
if (info.nextCommittedPeriod == 0 ||
info.currentCommittedPeriod == 0 &&
info.nextCommittedPeriod > previousPeriod ||
info.currentCommittedPeriod > previousPeriod) {
return (0, 0);
}
uint16 startPeriod = getStartPeriod(info, currentPeriod);
uint256 reward = 0;
bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX);
if (info.currentCommittedPeriod != 0) {
reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake);
processedPeriod1 = info.currentCommittedPeriod;
info.currentCommittedPeriod = 0;
if (reStake) {
_lockedPerPeriod[info.nextCommittedPeriod] += reward;
}
}
if (info.nextCommittedPeriod <= previousPeriod) {
reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake);
processedPeriod2 = info.nextCommittedPeriod;
info.nextCommittedPeriod = 0;
}
info.value += reward;
if (info.flags.bitSet(MEASURE_WORK_INDEX)) {
info.completedWork += reward;
}
addSnapshot(info, int256(reward));
emit Minted(_staker, previousPeriod, reward);
}
/**
* @notice Calculate reward for one period
* @param _info Staker structure
* @param _mintingPeriod Period for minting calculation
* @param _currentPeriod Current period
* @param _startPeriod Pre-calculated start period
*/
function mint(
StakerInfo storage _info,
uint16 _mintingPeriod,
uint16 _currentPeriod,
uint16 _startPeriod,
bool _reStake
)
internal returns (uint256 reward)
{
reward = 0;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) {
uint256 subStakeReward = mint(
_currentPeriod,
subStake.lockedValue,
_lockedPerPeriod[_mintingPeriod],
lastPeriod.sub16(_mintingPeriod));
reward += subStakeReward;
if (_reStake) {
subStake.lockedValue += uint128(subStakeReward);
}
}
}
return reward;
}
//-------------------------Slashing-------------------------
/**
* @notice Slash the staker's stake and reward the investigator
* @param _staker Staker's address
* @param _penalty Penalty
* @param _investigator Investigator
* @param _reward Reward for the investigator
*/
function slashStaker(
address _staker,
uint256 _penalty,
address _investigator,
uint256 _reward
)
public isInitialized
{
require(msg.sender == address(adjudicator));
require(_penalty > 0);
StakerInfo storage info = stakerInfo[_staker];
require(info.flags.bitSet(MIGRATED_INDEX));
if (info.value <= _penalty) {
_penalty = info.value;
}
info.value -= _penalty;
if (_reward > _penalty) {
_reward = _penalty;
}
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
uint16 startPeriod = getStartPeriod(info, currentPeriod);
(uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) =
getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod);
// Decrease the stake if amount of locked tokens in the current period more than staker has
uint256 lockedTokens = currentLock + currentAndNextLock;
if (info.value < lockedTokens) {
decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex);
}
// Decrease the stake if amount of locked tokens in the next period more than staker has
if (nextLock > 0) {
lockedTokens = nextLock + currentAndNextLock -
(currentAndNextLock > info.value ? currentAndNextLock - info.value : 0);
if (info.value < lockedTokens) {
decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES);
}
}
emit Slashed(_staker, _penalty, _investigator, _reward);
if (_penalty > _reward) {
unMint(_penalty - _reward);
}
// TODO change to withdrawal pattern (#1499)
if (_reward > 0) {
token.safeTransfer(_investigator, _reward);
}
addSnapshot(info, - int256(_penalty));
}
/**
* @notice Get the value of locked tokens for a staker in the current and the next period
* and find the shortest sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _nextPeriod Next period
* @param _startPeriod Pre-calculated start period
* @return currentLock Amount of tokens that locked in the current period and unlocked in the next period
* @return nextLock Amount of tokens that locked in the next period and not locked in the current period
* @return currentAndNextLock Amount of tokens that locked in the current period and in the next period
* @return shortestSubStakeIndex Index of the shortest sub stake
*/
function getLockedTokensAndShortestSubStake(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _nextPeriod,
uint16 _startPeriod
)
internal view returns (
uint256 currentLock,
uint256 nextLock,
uint256 currentAndNextLock,
uint256 shortestSubStakeIndex
)
{
uint16 minDuration = MAX_UINT16;
uint16 minLastPeriod = MAX_UINT16;
shortestSubStakeIndex = MAX_SUB_STAKES;
currentLock = 0;
nextLock = 0;
currentAndNextLock = 0;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (lastPeriod < subStake.firstPeriod) {
continue;
}
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _nextPeriod) {
currentAndNextLock += subStake.lockedValue;
} else if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod) {
currentLock += subStake.lockedValue;
} else if (subStake.firstPeriod <= _nextPeriod &&
lastPeriod >= _nextPeriod) {
nextLock += subStake.lockedValue;
}
uint16 duration = lastPeriod - subStake.firstPeriod;
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod &&
(lastPeriod < minLastPeriod ||
lastPeriod == minLastPeriod && duration < minDuration))
{
shortestSubStakeIndex = i;
minDuration = duration;
minLastPeriod = lastPeriod;
}
}
}
/**
* @notice Decrease short sub stakes
* @param _info Staker structure
* @param _penalty Penalty rate
* @param _decreasePeriod The period when the decrease begins
* @param _startPeriod Pre-calculated start period
* @param _shortestSubStakeIndex Index of the shortest period
*/
function decreaseSubStakes(
StakerInfo storage _info,
uint256 _penalty,
uint16 _decreasePeriod,
uint16 _startPeriod,
uint256 _shortestSubStakeIndex
)
internal
{
SubStakeInfo storage shortestSubStake = _info.subStakes[0];
uint16 minSubStakeLastPeriod = MAX_UINT16;
uint16 minSubStakeDuration = MAX_UINT16;
while(_penalty > 0) {
if (_shortestSubStakeIndex < MAX_SUB_STAKES) {
shortestSubStake = _info.subStakes[_shortestSubStakeIndex];
minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod);
minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod;
_shortestSubStakeIndex = MAX_SUB_STAKES;
} else {
(shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) =
getShortestSubStake(_info, _decreasePeriod, _startPeriod);
}
if (minSubStakeDuration == MAX_UINT16) {
break;
}
uint256 appliedPenalty = _penalty;
if (_penalty < shortestSubStake.lockedValue) {
shortestSubStake.lockedValue -= uint128(_penalty);
saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod);
_penalty = 0;
} else {
shortestSubStake.lastPeriod = _decreasePeriod - 1;
_penalty -= shortestSubStake.lockedValue;
appliedPenalty = shortestSubStake.lockedValue;
}
if (_info.currentCommittedPeriod >= _decreasePeriod &&
_info.currentCommittedPeriod <= minSubStakeLastPeriod)
{
_lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty;
}
if (_info.nextCommittedPeriod >= _decreasePeriod &&
_info.nextCommittedPeriod <= minSubStakeLastPeriod)
{
_lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty;
}
}
}
/**
* @notice Get the shortest sub stake
* @param _info Staker structure
* @param _currentPeriod Current period
* @param _startPeriod Pre-calculated start period
* @return shortestSubStake The shortest sub stake
* @return minSubStakeDuration Duration of the shortest sub stake
* @return minSubStakeLastPeriod Last period of the shortest sub stake
*/
function getShortestSubStake(
StakerInfo storage _info,
uint16 _currentPeriod,
uint16 _startPeriod
)
internal view returns (
SubStakeInfo storage shortestSubStake,
uint16 minSubStakeDuration,
uint16 minSubStakeLastPeriod
)
{
shortestSubStake = shortestSubStake;
minSubStakeDuration = MAX_UINT16;
minSubStakeLastPeriod = MAX_UINT16;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod);
if (lastPeriod < subStake.firstPeriod) {
continue;
}
uint16 duration = lastPeriod - subStake.firstPeriod;
if (subStake.firstPeriod <= _currentPeriod &&
lastPeriod >= _currentPeriod &&
(lastPeriod < minSubStakeLastPeriod ||
lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration))
{
shortestSubStake = subStake;
minSubStakeDuration = duration;
minSubStakeLastPeriod = lastPeriod;
}
}
}
/**
* @notice Save the old sub stake values to prevent decreasing reward for the previous period
* @dev Saving happens only if the previous period is committed
* @param _info Staker structure
* @param _firstPeriod First period of the old sub stake
* @param _lockedValue Locked value of the old sub stake
* @param _currentPeriod Current period, when the old sub stake is already unlocked
*/
function saveOldSubStake(
StakerInfo storage _info,
uint16 _firstPeriod,
uint256 _lockedValue,
uint16 _currentPeriod
)
internal
{
// Check that the old sub stake should be saved
bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 &&
_info.currentCommittedPeriod < _currentPeriod;
bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 &&
_info.nextCommittedPeriod < _currentPeriod;
bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod;
bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod;
if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) {
return;
}
// Try to find already existent proper old sub stake
uint16 previousPeriod = _currentPeriod - 1;
for (uint256 i = 0; i < _info.subStakes.length; i++) {
SubStakeInfo storage subStake = _info.subStakes[i];
if (subStake.lastPeriod == previousPeriod &&
((crosscurrentCommittedPeriod ==
(oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) &&
(crossnextCommittedPeriod ==
(oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod))))
{
subStake.lockedValue += uint128(_lockedValue);
return;
}
}
saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue);
}
//-------------Additional getters for stakers info-------------
/**
* @notice Return the length of the array of stakers
*/
function getStakersLength() external view returns (uint256) {
return stakers.length;
}
/**
* @notice Return the length of the array of sub stakes
*/
function getSubStakesLength(address _staker) external view returns (uint256) {
return stakerInfo[_staker].subStakes.length;
}
/**
* @notice Return the information about sub stake
*/
function getSubStakeInfo(address _staker, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (SubStakeInfo)
// TODO "virtual" only for tests, probably will be removed after #1512
external view virtual returns (
uint16 firstPeriod,
uint16 lastPeriod,
uint16 unlockingDuration,
uint128 lockedValue
)
{
SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index];
firstPeriod = info.firstPeriod;
lastPeriod = info.lastPeriod;
unlockingDuration = info.unlockingDuration;
lockedValue = info.lockedValue;
}
/**
* @notice Return the length of the array of past downtime
*/
function getPastDowntimeLength(address _staker) external view returns (uint256) {
return stakerInfo[_staker].pastDowntime.length;
}
/**
* @notice Return the information about past downtime
*/
function getPastDowntime(address _staker, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (Downtime)
external view returns (uint16 startPeriod, uint16 endPeriod)
{
Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index];
startPeriod = downtime.startPeriod;
endPeriod = downtime.endPeriod;
}
//------------------ ERC900 connectors ----------------------
function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){
return stakerInfo[_owner].history.getValueAt(_blockNumber);
}
function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){
return balanceHistory.getValueAt(_blockNumber);
}
function supportsHistory() external pure override returns (bool){
return true;
}
//------------------------Upgradeable------------------------
/**
* @dev Get StakerInfo structure by delegatecall
*/
function delegateGetStakerInfo(address _target, bytes32 _staker)
internal returns (StakerInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get SubStakeInfo structure by delegatecall
*/
function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index)
internal returns (SubStakeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get Downtime structure by delegatecall
*/
function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index)
internal returns (Downtime memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getPastDowntime.selector, 2, _staker, bytes32(_index));
assembly {
result := memoryAddress
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(delegateGet(_testTarget, this.lockedPerPeriod.selector,
bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD));
require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) ==
stakerFromWorker[address(0)]);
require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length);
if (stakers.length == 0) {
return;
}
address stakerAddress = stakers[0];
require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress);
StakerInfo storage info = stakerInfo[stakerAddress];
bytes32 staker = bytes32(uint256(stakerAddress));
StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker);
require(infoToCheck.value == info.value &&
infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod &&
infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod &&
infoToCheck.flags == info.flags &&
infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod &&
infoToCheck.completedWork == info.completedWork &&
infoToCheck.worker == info.worker &&
infoToCheck.workerStartPeriod == info.workerStartPeriod);
require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) ==
info.pastDowntime.length);
for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) {
Downtime storage downtime = info.pastDowntime[i];
Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i);
require(downtimeToCheck.startPeriod == downtime.startPeriod &&
downtimeToCheck.endPeriod == downtime.endPeriod);
}
require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length);
for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) {
SubStakeInfo storage subStakeInfo = info.subStakes[i];
SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i);
require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod &&
subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod &&
subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration &&
subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue);
}
// it's not perfect because checks not only slot value but also decoding
// at least without additional functions
require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) ==
totalStakedForAt(stakerAddress, block.number));
require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) ==
totalStakedAt(block.number));
if (info.worker != address(0)) {
require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) ==
stakerFromWorker[info.worker]);
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// Create fake period
_lockedPerPeriod[RESERVED_PERIOD] = 111;
// Create fake worker
stakerFromWorker[address(0)] = address(this);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
// Minimum interface to interact with Aragon's Aggregator
interface IERC900History {
function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256);
function totalStakedAt(uint256 blockNumber) external view returns (uint256);
function supportsHistory() external pure returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./NuCypherToken.sol";
import "../zeppelin/math/Math.sol";
import "./proxy/Upgradeable.sol";
import "./lib/AdditionalMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
/**
* @title Issuer
* @notice Contract for calculation of issued tokens
* @dev |v3.4.1|
*/
abstract contract Issuer is Upgradeable {
using SafeERC20 for NuCypherToken;
using AdditionalMath for uint32;
event Donated(address indexed sender, uint256 value);
/// Issuer is initialized with a reserved reward
event Initialized(uint256 reservedReward);
uint128 constant MAX_UINT128 = uint128(0) - 1;
NuCypherToken public immutable token;
uint128 public immutable totalSupply;
// d * k2
uint256 public immutable mintingCoefficient;
// k1
uint256 public immutable lockDurationCoefficient1;
// k2
uint256 public immutable lockDurationCoefficient2;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
// kmax
uint16 public immutable maximumRewardedPeriods;
uint256 public immutable firstPhaseMaxIssuance;
uint256 public immutable firstPhaseTotalSupply;
/**
* Current supply is used in the minting formula and is stored to prevent different calculation
* for stakers which get reward in the same period. There are two values -
* supply for previous period (used in formula) and supply for current period which accumulates value
* before end of period.
*/
uint128 public previousPeriodSupply;
uint128 public currentPeriodSupply;
uint16 public currentMintingPeriod;
/**
* @notice Constructor sets address of token contract and coefficients for minting
* @dev Minting formula for one sub-stake in one period for the first phase
firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2
* @dev Minting formula for one sub-stake in one period for the second phase
(totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2
if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods
* @param _token Token contract
* @param _genesisHoursPerPeriod Size of period in hours at genesis
* @param _hoursPerPeriod Size of period in hours
* @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays,
* only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2.
* See Equation 10 in Staking Protocol & Economics paper
* @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent
* to which a stake's lock duration affects the subsidy it receives. Affects stakers differently.
* Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier)
* where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration
* no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1.
* See Equation 8 in Staking Protocol & Economics paper.
* @param _firstPhaseTotalSupply Total supply for the first phase
* @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1.
* See Equation 7 in Staking Protocol & Economics paper.
*/
constructor(
NuCypherToken _token,
uint32 _genesisHoursPerPeriod,
uint32 _hoursPerPeriod,
uint256 _issuanceDecayCoefficient,
uint256 _lockDurationCoefficient1,
uint256 _lockDurationCoefficient2,
uint16 _maximumRewardedPeriods,
uint256 _firstPhaseTotalSupply,
uint256 _firstPhaseMaxIssuance
) {
uint256 localTotalSupply = _token.totalSupply();
require(localTotalSupply > 0 &&
_issuanceDecayCoefficient != 0 &&
_hoursPerPeriod != 0 &&
_genesisHoursPerPeriod != 0 &&
_genesisHoursPerPeriod <= _hoursPerPeriod &&
_lockDurationCoefficient1 != 0 &&
_lockDurationCoefficient2 != 0 &&
_maximumRewardedPeriods != 0);
require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported");
uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1;
uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2;
require(maxLockDurationCoefficient > _maximumRewardedPeriods &&
localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 &&
// worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply
localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient &&
// worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`,
// when currentSupply == 0, lockedValue == totalSupply
localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply ==
maxLockDurationCoefficient,
"Specified parameters cause overflow");
require(maxLockDurationCoefficient <= _lockDurationCoefficient2,
"Resulting locking duration coefficient must be less than 1");
require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase");
require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high");
token = _token;
secondsPerPeriod = _hoursPerPeriod.mul32(1 hours);
genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours);
lockDurationCoefficient1 = _lockDurationCoefficient1;
lockDurationCoefficient2 = _lockDurationCoefficient2;
maximumRewardedPeriods = _maximumRewardedPeriods;
firstPhaseTotalSupply = _firstPhaseTotalSupply;
firstPhaseMaxIssuance = _firstPhaseMaxIssuance;
totalSupply = uint128(localTotalSupply);
mintingCoefficient = localMintingCoefficient;
}
/**
* @dev Checks contract initialization
*/
modifier isInitialized()
{
require(currentMintingPeriod != 0);
_;
}
/**
* @return Number of current period
*/
function getCurrentPeriod() public view returns (uint16) {
return uint16(block.timestamp / secondsPerPeriod);
}
/**
* @return Recalculate period value using new basis
*/
function recalculatePeriod(uint16 _period) internal view returns (uint16) {
return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod);
}
/**
* @notice Initialize reserved tokens for reward
*/
function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner {
require(currentMintingPeriod == 0);
// Reserved reward must be sufficient for at least one period of the first phase
require(firstPhaseMaxIssuance <= _reservedReward);
currentMintingPeriod = getCurrentPeriod();
currentPeriodSupply = totalSupply - uint128(_reservedReward);
previousPeriodSupply = currentPeriodSupply;
token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward);
emit Initialized(_reservedReward);
}
/**
* @notice Function to mint tokens for one period.
* @param _currentPeriod Current period number.
* @param _lockedValue The amount of tokens that were locked by user in specified period.
* @param _totalLockedValue The amount of tokens that were locked by all users in specified period.
* @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period.
* @return amount Amount of minted tokens.
*/
function mint(
uint16 _currentPeriod,
uint256 _lockedValue,
uint256 _totalLockedValue,
uint16 _allLockedPeriods
)
internal returns (uint256 amount)
{
if (currentPeriodSupply == totalSupply) {
return 0;
}
if (_currentPeriod > currentMintingPeriod) {
previousPeriodSupply = currentPeriodSupply;
currentMintingPeriod = _currentPeriod;
}
uint256 currentReward;
uint256 coefficient;
// first phase
// firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2)
if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) {
currentReward = firstPhaseMaxIssuance;
coefficient = lockDurationCoefficient2;
// second phase
// (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2)
} else {
currentReward = totalSupply - previousPeriodSupply;
coefficient = mintingCoefficient;
}
uint256 allLockedPeriods =
AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1;
amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) /
(_totalLockedValue * coefficient);
// rounding the last reward
uint256 maxReward = getReservedReward();
if (amount == 0) {
amount = 1;
} else if (amount > maxReward) {
amount = maxReward;
}
currentPeriodSupply += uint128(amount);
}
/**
* @notice Return tokens for future minting
* @param _amount Amount of tokens
*/
function unMint(uint256 _amount) internal {
previousPeriodSupply -= uint128(_amount);
currentPeriodSupply -= uint128(_amount);
}
/**
* @notice Donate sender's tokens. Amount of tokens will be returned for future minting
* @param _value Amount to donate
*/
function donate(uint256 _value) external isInitialized {
token.safeTransferFrom(msg.sender, address(this), _value);
unMint(_value);
emit Donated(msg.sender, _value);
}
/**
* @notice Returns the number of tokens that can be minted
*/
function getReservedReward() public view returns (uint256) {
return totalSupply - currentPeriodSupply;
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod);
require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply);
require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply);
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
// recalculate currentMintingPeriod if needed
if (currentMintingPeriod > getCurrentPeriod()) {
currentMintingPeriod = recalculatePeriod(currentMintingPeriod);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/token/ERC20/ERC20.sol";
import "../zeppelin/token/ERC20/ERC20Detailed.sol";
/**
* @title NuCypherToken
* @notice ERC20 token
* @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred.
*/
contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) {
/**
* @notice Set amount of tokens
* @param _totalSupplyOfTokens Total number of tokens
*/
constructor (uint256 _totalSupplyOfTokens) {
_mint(msg.sender, _totalSupplyOfTokens);
}
/**
* @notice Approves and then calls the receiving contract
*
* @dev call the receiveApproval function on the contract you want to be notified.
* receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
*/
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData)
external returns (bool success)
{
approve(_spender, _value);
TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* @dev Interface to use the receiveApproval method
*/
interface TokenRecipient {
/**
* @notice Receives a notification of approval of the transfer
* @param _from Sender of approval
* @param _value The amount of tokens to be spent
* @param _tokenContract Address of the token contract
* @param _extraData Extra data
*/
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view override returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public override returns (bool) {
_transfer(msg.sender, 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 override returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(value == 0 || _allowed[msg.sender][spender] == 0);
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public override returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
abstract contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
/**
* @notice Base contract for upgradeable contract
* @dev Inherited contract should implement verifyState(address) method by checking storage variables
* (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address)
* if it is using constructor parameters by coping this parameters to the dispatcher storage
*/
abstract contract Upgradeable is Ownable {
event StateVerified(address indexed testTarget, address sender);
event UpgradeFinished(address indexed target, address sender);
/**
* @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher
* Stored data actually lives in the Dispatcher
* However the storage layout is specified here in the implementing contracts
*/
address public target;
/**
* @dev Previous contract address (if available). Used for rollback
*/
address public previousTarget;
/**
* @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value
*/
uint8 public isUpgrade;
/**
* @dev Guarantees that next slot will be separated from the previous
*/
uint256 stubSlot;
/**
* @dev Constants for `isUpgrade` field
*/
uint8 constant UPGRADE_FALSE = 1;
uint8 constant UPGRADE_TRUE = 2;
/**
* @dev Checks that function executed while upgrading
* Recommended to add to `verifyState` and `finishUpgrade` methods
*/
modifier onlyWhileUpgrading()
{
require(isUpgrade == UPGRADE_TRUE);
_;
}
/**
* @dev Method for verifying storage state.
* Should check that new target contract returns right storage value
*/
function verifyState(address _testTarget) public virtual onlyWhileUpgrading {
emit StateVerified(_testTarget, msg.sender);
}
/**
* @dev Copy values from the new target to the current storage
* @param _target New target contract address
*/
function finishUpgrade(address _target) public virtual onlyWhileUpgrading {
emit UpgradeFinished(_target, msg.sender);
}
/**
* @dev Base method to get data
* @param _target Target to call
* @param _selector Method selector
* @param _numberOfArguments Number of used arguments
* @param _argument1 First method argument
* @param _argument2 Second method argument
* @return memoryAddress Address in memory where the data is located
*/
function delegateGetData(
address _target,
bytes4 _selector,
uint8 _numberOfArguments,
bytes32 _argument1,
bytes32 _argument2
)
internal returns (bytes32 memoryAddress)
{
assembly {
memoryAddress := mload(0x40)
mstore(memoryAddress, _selector)
if gt(_numberOfArguments, 0) {
mstore(add(memoryAddress, 0x04), _argument1)
}
if gt(_numberOfArguments, 1) {
mstore(add(memoryAddress, 0x24), _argument2)
}
switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0)
case 0 {
revert(memoryAddress, 0)
}
default {
returndatacopy(memoryAddress, 0x0, returndatasize())
}
}
}
/**
* @dev Call "getter" without parameters.
* Result should not exceed 32 bytes
*/
function delegateGet(address _target, bytes4 _selector)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0);
assembly {
result := mload(memoryAddress)
}
}
/**
* @dev Call "getter" with one parameter.
* Result should not exceed 32 bytes
*/
function delegateGet(address _target, bytes4 _selector, bytes32 _argument)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0);
assembly {
result := mload(memoryAddress)
}
}
/**
* @dev Call "getter" with two parameters.
* Result should not exceed 32 bytes
*/
function delegateGet(
address _target,
bytes4 _selector,
bytes32 _argument1,
bytes32 _argument2
)
internal returns (uint256 result)
{
bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2);
assembly {
result := mload(memoryAddress)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
abstract 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 () {
_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 virtual 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;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/math/SafeMath.sol";
/**
* @notice Additional math operations
*/
library AdditionalMath {
using SafeMath for uint256;
function max16(uint16 a, uint16 b) internal pure returns (uint16) {
return a >= b ? a : b;
}
function min16(uint16 a, uint16 b) internal pure returns (uint16) {
return a < b ? a : b;
}
/**
* @notice Division and ceil
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return (a.add(b) - 1) / b;
}
/**
* @dev Adds signed value to unsigned value, throws on overflow.
*/
function addSigned(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.add(uint256(b));
} else {
return a.sub(uint256(-b));
}
}
/**
* @dev Subtracts signed value from unsigned value, throws on overflow.
*/
function subSigned(uint256 a, int256 b) internal pure returns (uint256) {
if (b >= 0) {
return a.sub(uint256(b));
} else {
return a.add(uint256(-b));
}
}
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul32(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add16(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub16(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds signed value to unsigned value, throws on overflow.
*/
function addSigned16(uint16 a, int16 b) internal pure returns (uint16) {
if (b >= 0) {
return add16(a, uint16(b));
} else {
return sub16(a, uint16(-b));
}
}
/**
* @dev Subtracts signed value from unsigned value, throws on overflow.
*/
function subSigned16(uint16 a, int16 b) internal pure returns (uint16) {
if (b >= 0) {
return sub16(a, uint16(b));
} else {
return add16(a, uint16(-b));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
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));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol
*/
library Bits {
uint256 internal constant ONE = uint256(1);
/**
* @notice Sets the bit at the given 'index' in 'self' to:
* '1' - if the bit is '0'
* '0' - if the bit is '1'
* @return The modified value
*/
function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) {
return self ^ ONE << index;
}
/**
* @notice Get the value of the bit at the given 'index' in 'self'.
*/
function bit(uint256 self, uint8 index) internal pure returns (uint8) {
return uint8(self >> index & 1);
}
/**
* @notice Check if the bit at the given 'index' in 'self' is set.
* @return 'true' - if the value of the bit is '1',
* 'false' - if the value of the bit is '0'
*/
function bitSet(uint256 self, uint8 index) internal pure returns (bool) {
return self >> index & 1 == 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @title Snapshot
* @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value)
* 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers
* @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately.
* Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol)
* On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing
*/
library Snapshot {
function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) {
return uint128(uint256(_time) << 96 | uint256(_value));
}
function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){
time = uint32(bytes4(bytes16(_snapshot)));
value = uint96(_snapshot);
}
function addSnapshot(uint128[] storage _self, uint256 _value) internal {
addSnapshot(_self, block.number, _value);
}
function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal {
uint256 length = _self.length;
if (length != 0) {
(uint32 currentTime, ) = decodeSnapshot(_self[length - 1]);
if (uint32(_time) == currentTime) {
_self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value));
return;
} else if (uint32(_time) < currentTime){
revert();
}
}
_self.push(encodeSnapshot(uint32(_time), uint96(_value)));
}
function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) {
uint256 length = _self.length;
if (length > 0) {
return decodeSnapshot(_self[length - 1]);
}
return (0, 0);
}
function lastValue(uint128[] storage _self) internal view returns (uint96) {
(, uint96 value) = lastSnapshot(_self);
return value;
}
function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) {
uint32 _time = uint32(_time256);
uint256 length = _self.length;
// Short circuit if there's no checkpoints yet
// Note that this also lets us avoid using SafeMath later on, as we've established that
// there must be at least one checkpoint
if (length == 0) {
return 0;
}
// Check last checkpoint
uint256 lastIndex = length - 1;
(uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]);
if (_time >= snapshotTime) {
return snapshotValue;
}
// Check first checkpoint (if not already checked with the above check on last)
(snapshotTime, snapshotValue) = decodeSnapshot(_self[0]);
if (length == 1 || _time < snapshotTime) {
return 0;
}
// Do binary search
// As we've already checked both ends, we don't need to check the last checkpoint again
uint256 low = 0;
uint256 high = lastIndex - 1;
uint32 midTime;
uint96 midValue;
while (high > low) {
uint256 mid = (high + low + 1) / 2; // average, ceil round
(midTime, midValue) = decodeSnapshot(_self[mid]);
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// Note that we don't need SafeMath here because mid must always be greater than 0
// from the while condition
high = mid - 1;
} else {
// _time == midTime
return midValue;
}
}
(, snapshotValue) = decodeSnapshot(_self[low]);
return snapshotValue;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
interface IForwarder {
function isForwarder() external pure returns (bool);
function canForward(address sender, bytes calldata evmCallScript) external view returns (bool);
function forward(bytes calldata evmCallScript) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
interface TokenManager {
function mint(address _receiver, uint256 _amount) external;
function issue(uint256 _amount) external;
function assign(address _receiver, uint256 _amount) external;
function burn(address _holder, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.7.0;
import "./IForwarder.sol";
// Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol
interface Voting is IForwarder{
enum VoterState { Absent, Yea, Nay }
// Public getters
function token() external returns (address);
function supportRequiredPct() external returns (uint64);
function minAcceptQuorumPct() external returns (uint64);
function voteTime() external returns (uint64);
function votesLength() external returns (uint256);
// Setters
function changeSupportRequiredPct(uint64 _supportRequiredPct) external;
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external;
// Creating new votes
function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId);
function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided)
external returns (uint256 voteId);
// Voting
function canVote(uint256 _voteId, address _voter) external view returns (bool);
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external;
// Executing a passed vote
function canExecute(uint256 _voteId) external view returns (bool);
function executeVote(uint256 _voteId) external;
// Additional info
function getVote(uint256 _voteId) external view
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes memory script
);
function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/math/SafeMath.sol";
/**
* @notice Multi-signature contract with off-chain signing
*/
contract MultiSig {
using SafeMath for uint256;
event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value);
event OwnerAdded(address indexed owner);
event OwnerRemoved(address indexed owner);
event RequirementChanged(uint16 required);
uint256 constant public MAX_OWNER_COUNT = 50;
uint256 public nonce;
uint8 public required;
mapping (address => bool) public isOwner;
address[] public owners;
/**
* @notice Only this contract can call method
*/
modifier onlyThisContract() {
require(msg.sender == address(this));
_;
}
receive() external payable {}
/**
* @param _required Number of required signings
* @param _owners List of initial owners.
*/
constructor (uint8 _required, address[] memory _owners) {
require(_owners.length <= MAX_OWNER_COUNT &&
_required <= _owners.length &&
_required > 0);
for (uint256 i = 0; i < _owners.length; i++) {
address owner = _owners[i];
require(!isOwner[owner] && owner != address(0));
isOwner[owner] = true;
}
owners = _owners;
required = _required;
}
/**
* @notice Get unsigned hash for transaction parameters
* @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191
* @param _sender Trustee who will execute the transaction
* @param _destination Destination address
* @param _value Amount of ETH to transfer
* @param _data Call data
* @param _nonce Nonce
*/
function getUnsignedTransactionHash(
address _sender,
address _destination,
uint256 _value,
bytes memory _data,
uint256 _nonce
)
public view returns (bytes32)
{
return keccak256(
abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce));
}
/**
* @dev Note that address recovered from signatures must be strictly increasing
* @param _sigV Array of signatures values V
* @param _sigR Array of signatures values R
* @param _sigS Array of signatures values S
* @param _destination Destination address
* @param _value Amount of ETH to transfer
* @param _data Call data
*/
function execute(
uint8[] calldata _sigV,
bytes32[] calldata _sigR,
bytes32[] calldata _sigS,
address _destination,
uint256 _value,
bytes calldata _data
)
external
{
require(_sigR.length >= required &&
_sigR.length == _sigS.length &&
_sigR.length == _sigV.length);
bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce);
address lastAdd = address(0);
for (uint256 i = 0; i < _sigR.length; i++) {
address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]);
require(recovered > lastAdd && isOwner[recovered]);
lastAdd = recovered;
}
emit Executed(msg.sender, nonce, _destination, _value);
nonce = nonce.add(1);
(bool callSuccess,) = _destination.call{value: _value}(_data);
require(callSuccess);
}
/**
* @notice Allows to add a new owner
* @dev Transaction has to be sent by `execute` method.
* @param _owner Address of new owner
*/
function addOwner(address _owner)
external
onlyThisContract
{
require(owners.length < MAX_OWNER_COUNT &&
_owner != address(0) &&
!isOwner[_owner]);
isOwner[_owner] = true;
owners.push(_owner);
emit OwnerAdded(_owner);
}
/**
* @notice Allows to remove an owner
* @dev Transaction has to be sent by `execute` method.
* @param _owner Address of owner
*/
function removeOwner(address _owner)
external
onlyThisContract
{
require(owners.length > required && isOwner[_owner]);
isOwner[_owner] = false;
for (uint256 i = 0; i < owners.length - 1; i++) {
if (owners[i] == _owner) {
owners[i] = owners[owners.length - 1];
break;
}
}
owners.pop();
emit OwnerRemoved(_owner);
}
/**
* @notice Returns the number of owners of this MultiSig
*/
function getNumberOfOwners() external view returns (uint256) {
return owners.length;
}
/**
* @notice Allows to change the number of required signatures
* @dev Transaction has to be sent by `execute` method
* @param _required Number of required signatures
*/
function changeRequirement(uint8 _required)
external
onlyThisContract
{
require(_required <= owners.length && _required > 0);
required = _required;
emit RequirementChanged(_required);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/token/ERC20/SafeERC20.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/math/Math.sol";
import "../zeppelin/utils/Address.sol";
import "./lib/AdditionalMath.sol";
import "./lib/SignatureVerifier.sol";
import "./StakingEscrow.sol";
import "./NuCypherToken.sol";
import "./proxy/Upgradeable.sol";
/**
* @title PolicyManager
* @notice Contract holds policy data and locks accrued policy fees
* @dev |v6.3.1|
*/
contract PolicyManager is Upgradeable {
using SafeERC20 for NuCypherToken;
using SafeMath for uint256;
using AdditionalMath for uint256;
using AdditionalMath for int256;
using AdditionalMath for uint16;
using Address for address payable;
event PolicyCreated(
bytes16 indexed policyId,
address indexed sponsor,
address indexed owner,
uint256 feeRate,
uint64 startTimestamp,
uint64 endTimestamp,
uint256 numberOfNodes
);
event ArrangementRevoked(
bytes16 indexed policyId,
address indexed sender,
address indexed node,
uint256 value
);
event RefundForArrangement(
bytes16 indexed policyId,
address indexed sender,
address indexed node,
uint256 value
);
event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value);
event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value);
event MinFeeRateSet(address indexed node, uint256 value);
// TODO #1501
// Range range
event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max);
event Withdrawn(address indexed node, address indexed recipient, uint256 value);
struct ArrangementInfo {
address node;
uint256 indexOfDowntimePeriods;
uint16 lastRefundedPeriod;
}
struct Policy {
bool disabled;
address payable sponsor;
address owner;
uint128 feeRate;
uint64 startTimestamp;
uint64 endTimestamp;
uint256 reservedSlot1;
uint256 reservedSlot2;
uint256 reservedSlot3;
uint256 reservedSlot4;
uint256 reservedSlot5;
ArrangementInfo[] arrangements;
}
struct NodeInfo {
uint128 fee;
uint16 previousFeePeriod;
uint256 feeRate;
uint256 minFeeRate;
mapping (uint16 => int256) stub; // former slot for feeDelta
mapping (uint16 => int256) feeDelta;
}
// TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512
struct MemoryNodeInfo {
uint128 fee;
uint16 previousFeePeriod;
uint256 feeRate;
uint256 minFeeRate;
}
struct Range {
uint128 min;
uint128 defaultValue;
uint128 max;
}
bytes16 internal constant RESERVED_POLICY_ID = bytes16(0);
address internal constant RESERVED_NODE = address(0);
uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1);
// controlled overflow to get max int256
int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1);
StakingEscrow public immutable escrow;
uint32 public immutable genesisSecondsPerPeriod;
uint32 public immutable secondsPerPeriod;
mapping (bytes16 => Policy) public policies;
mapping (address => NodeInfo) public nodes;
Range public feeRateRange;
uint64 public resetTimestamp;
/**
* @notice Constructor sets address of the escrow contract
* @dev Put same address in both inputs variables except when migration is happening
* @param _escrowDispatcher Address of escrow dispatcher
* @param _escrowImplementation Address of escrow implementation
*/
constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) {
escrow = _escrowDispatcher;
// if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error
uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod();
require(localSecondsPerPeriod > 0);
secondsPerPeriod = localSecondsPerPeriod;
uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod();
require(localgenesisSecondsPerPeriod > 0);
genesisSecondsPerPeriod = localgenesisSecondsPerPeriod;
// handle case when we deployed new StakingEscrow but not yet upgraded
if (_escrowDispatcher != _escrowImplementation) {
require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod ||
_escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod);
}
}
/**
* @dev Checks that sender is the StakingEscrow contract
*/
modifier onlyEscrowContract()
{
require(msg.sender == address(escrow));
_;
}
/**
* @return Number of current period
*/
function getCurrentPeriod() public view returns (uint16) {
return uint16(block.timestamp / secondsPerPeriod);
}
/**
* @return Recalculate period value using new basis
*/
function recalculatePeriod(uint16 _period) internal view returns (uint16) {
return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod);
}
/**
* @notice Register a node
* @param _node Node address
* @param _period Initial period
*/
function register(address _node, uint16 _period) external onlyEscrowContract {
NodeInfo storage nodeInfo = nodes[_node];
require(nodeInfo.previousFeePeriod == 0 && _period < getCurrentPeriod());
nodeInfo.previousFeePeriod = _period;
}
/**
* @notice Migrate from the old period length to the new one
* @param _node Node address
*/
function migrate(address _node) external onlyEscrowContract {
NodeInfo storage nodeInfo = nodes[_node];
// with previous period length any previousFeePeriod will be greater than current period
// this is a sign of not migrated node
require(nodeInfo.previousFeePeriod >= getCurrentPeriod());
nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod);
nodeInfo.feeRate = 0;
}
/**
* @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range')
*/
// TODO # 1501
// function setFeeRateRange(Range calldata _range) external onlyOwner {
function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner {
require(_min <= _default && _default <= _max);
feeRateRange = Range(_min, _default, _max);
emit FeeRateRangeSet(msg.sender, _min, _default, _max);
}
/**
* @notice Set the minimum acceptable fee rate (set by staker for their associated worker)
* @dev Input value must fall within `feeRateRange` (global fee range)
*/
function setMinFeeRate(uint256 _minFeeRate) external {
require(_minFeeRate >= feeRateRange.min &&
_minFeeRate <= feeRateRange.max,
"The staker's min fee rate must fall within the global fee range");
NodeInfo storage nodeInfo = nodes[msg.sender];
if (nodeInfo.minFeeRate == _minFeeRate) {
return;
}
nodeInfo.minFeeRate = _minFeeRate;
emit MinFeeRateSet(msg.sender, _minFeeRate);
}
/**
* @notice Get the minimum acceptable fee rate (set by staker for their associated worker)
*/
function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) {
// if minFeeRate has not been set or chosen value falls outside the global fee range
// a default value is returned instead
if (_nodeInfo.minFeeRate == 0 ||
_nodeInfo.minFeeRate < feeRateRange.min ||
_nodeInfo.minFeeRate > feeRateRange.max) {
return feeRateRange.defaultValue;
} else {
return _nodeInfo.minFeeRate;
}
}
/**
* @notice Get the minimum acceptable fee rate (set by staker for their associated worker)
*/
function getMinFeeRate(address _node) public view returns (uint256) {
NodeInfo storage nodeInfo = nodes[_node];
return getMinFeeRate(nodeInfo);
}
/**
* @notice Create policy
* @dev Generate policy id before creation
* @param _policyId Policy id
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of the policy in seconds
* @param _nodes Nodes that will handle policy
*/
function createPolicy(
bytes16 _policyId,
address _policyOwner,
uint64 _endTimestamp,
address[] calldata _nodes
)
external payable
{
require(
_endTimestamp > block.timestamp &&
msg.value > 0
);
require(address(this).balance <= MAX_BALANCE);
uint16 currentPeriod = getCurrentPeriod();
uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfPeriods = endPeriod - currentPeriod;
uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods);
require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value);
Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length);
for (uint256 i = 0; i < _nodes.length; i++) {
address node = _nodes[i];
addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate));
policy.arrangements.push(ArrangementInfo(node, 0, 0));
}
}
/**
* @notice Create multiple policies with the same owner, nodes and length
* @dev Generate policy ids before creation
* @param _policyIds Policy ids
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of all policies in seconds
* @param _nodes Nodes that will handle all policies
*/
function createPolicies(
bytes16[] calldata _policyIds,
address _policyOwner,
uint64 _endTimestamp,
address[] calldata _nodes
)
external payable
{
require(
_endTimestamp > block.timestamp &&
msg.value > 0 &&
_policyIds.length > 1
);
require(address(this).balance <= MAX_BALANCE);
uint16 currentPeriod = getCurrentPeriod();
uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfPeriods = endPeriod - currentPeriod;
uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length);
require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value);
for (uint256 i = 0; i < _policyIds.length; i++) {
Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length);
for (uint256 j = 0; j < _nodes.length; j++) {
policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0));
}
}
int256 fee = int256(_policyIds.length * feeRate);
for (uint256 i = 0; i < _nodes.length; i++) {
address node = _nodes[i];
addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee);
}
}
/**
* @notice Create policy
* @param _policyId Policy id
* @param _policyOwner Policy owner. Zero address means sender is owner
* @param _endTimestamp End timestamp of the policy in seconds
* @param _feeRate Fee rate for policy
* @param _nodesLength Number of nodes that will handle policy
*/
function createPolicy(
bytes16 _policyId,
address _policyOwner,
uint64 _endTimestamp,
uint128 _feeRate,
uint256 _nodesLength
)
internal returns (Policy storage policy)
{
policy = policies[_policyId];
require(
_policyId != RESERVED_POLICY_ID &&
policy.feeRate == 0 &&
!policy.disabled
);
policy.sponsor = msg.sender;
policy.startTimestamp = uint64(block.timestamp);
policy.endTimestamp = _endTimestamp;
policy.feeRate = _feeRate;
if (_policyOwner != msg.sender && _policyOwner != address(0)) {
policy.owner = _policyOwner;
}
emit PolicyCreated(
_policyId,
msg.sender,
_policyOwner == address(0) ? msg.sender : _policyOwner,
_feeRate,
policy.startTimestamp,
policy.endTimestamp,
_nodesLength
);
}
/**
* @notice Increase fee rate for specified node
* @param _currentPeriod Current period
* @param _endPeriod End period of policy
* @param _node Node that will handle policy
* @param _feeRate Fee rate for one policy
* @param _overallFeeRate Fee rate for all policies
*/
function addFeeToNode(
uint16 _currentPeriod,
uint16 _endPeriod,
address _node,
uint128 _feeRate,
int256 _overallFeeRate
)
internal
{
require(_node != RESERVED_NODE);
NodeInfo storage nodeInfo = nodes[_node];
require(nodeInfo.previousFeePeriod != 0 &&
nodeInfo.previousFeePeriod < _currentPeriod &&
_feeRate >= getMinFeeRate(nodeInfo));
// Check default value for feeDelta
if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate;
} else {
// Overflow protection removed, because ETH total supply less than uint255/int256
nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate;
}
if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate;
} else {
nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate;
}
// Reset to default value if needed
if (nodeInfo.feeDelta[_currentPeriod] == 0) {
nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA;
}
if (nodeInfo.feeDelta[_endPeriod] == 0) {
nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA;
}
}
/**
* @notice Get policy owner
*/
function getPolicyOwner(bytes16 _policyId) public view returns (address) {
Policy storage policy = policies[_policyId];
return policy.owner == address(0) ? policy.sponsor : policy.owner;
}
/**
* @notice Call from StakingEscrow to update node info once per period.
* Set default `feeDelta` value for specified period and update node fee
* @param _node Node address
* @param _processedPeriod1 Processed period
* @param _processedPeriod2 Processed period
* @param _periodToSetDefault Period to set
*/
function ping(
address _node,
uint16 _processedPeriod1,
uint16 _processedPeriod2,
uint16 _periodToSetDefault
)
external onlyEscrowContract
{
NodeInfo storage node = nodes[_node];
// protection from calling not migrated node, see migrate()
require(node.previousFeePeriod <= getCurrentPeriod());
if (_processedPeriod1 != 0) {
updateFee(node, _processedPeriod1);
}
if (_processedPeriod2 != 0) {
updateFee(node, _processedPeriod2);
}
// This code increases gas cost for node in trade of decreasing cost for policy sponsor
if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) {
node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA;
}
}
/**
* @notice Update node fee
* @param _info Node info structure
* @param _period Processed period
*/
function updateFee(NodeInfo storage _info, uint16 _period) internal {
if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) {
return;
}
for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) {
int256 delta = _info.feeDelta[i];
if (delta == DEFAULT_FEE_DELTA) {
// gas refund
_info.feeDelta[i] = 0;
continue;
}
_info.feeRate = _info.feeRate.addSigned(delta);
// gas refund
_info.feeDelta[i] = 0;
}
_info.previousFeePeriod = _period;
_info.fee += uint128(_info.feeRate);
}
/**
* @notice Withdraw fee by node
*/
function withdraw() external returns (uint256) {
return withdraw(msg.sender);
}
/**
* @notice Withdraw fee by node
* @param _recipient Recipient of the fee
*/
function withdraw(address payable _recipient) public returns (uint256) {
NodeInfo storage node = nodes[msg.sender];
uint256 fee = node.fee;
require(fee != 0);
node.fee = 0;
_recipient.sendValue(fee);
emit Withdrawn(msg.sender, _recipient, fee);
return fee;
}
/**
* @notice Calculate amount of refund
* @param _policy Policy
* @param _arrangement Arrangement
*/
function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement)
internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
uint16 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod);
uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod));
uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod);
uint16 downtimePeriods = 0;
uint256 length = escrow.getPastDowntimeLength(_arrangement.node);
uint256 initialIndexOfDowntimePeriods;
if (_arrangement.lastRefundedPeriod == 0) {
initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod);
} else {
initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods;
}
for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods;
indexOfDowntimePeriods < length;
indexOfDowntimePeriods++)
{
(uint16 startPeriod, uint16 endPeriod) =
escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods);
if (startPeriod > maxPeriod) {
break;
} else if (endPeriod < minPeriod) {
continue;
}
downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod)
.sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1;
if (maxPeriod <= endPeriod) {
break;
}
}
uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node);
if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) {
// Overflow protection removed:
// lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1
downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod);
}
refundValue = _policy.feeRate * downtimePeriods;
lastRefundedPeriod = maxPeriod + 1;
}
/**
* @notice Revoke/refund arrangement/policy by the sponsor
* @param _policyId Policy id
* @param _node Node that will be excluded or RESERVED_NODE if full policy should be used
( @param _forceRevoke Force revoke arrangement/policy
*/
function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke)
internal returns (uint256 refundValue)
{
refundValue = 0;
Policy storage policy = policies[_policyId];
require(!policy.disabled && policy.startTimestamp >= resetTimestamp);
uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1;
uint256 numberOfActive = policy.arrangements.length;
uint256 i = 0;
for (; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
address node = arrangement.node;
if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) {
numberOfActive--;
continue;
}
uint256 nodeRefundValue;
(nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) =
calculateRefundValue(policy, arrangement);
if (_forceRevoke) {
NodeInfo storage nodeInfo = nodes[node];
// Check default value for feeDelta
uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod;
if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate);
} else {
nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate);
}
if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) {
nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate);
} else {
nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate);
}
// Reset to default value if needed
if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) {
nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA;
}
if (nodeInfo.feeDelta[endPeriod] == 0) {
nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA;
}
nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate;
}
if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) {
arrangement.node = RESERVED_NODE;
arrangement.indexOfDowntimePeriods = 0;
arrangement.lastRefundedPeriod = 0;
numberOfActive--;
emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue);
} else {
emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue);
}
refundValue += nodeRefundValue;
if (_node != RESERVED_NODE) {
break;
}
}
address payable policySponsor = policy.sponsor;
if (_node == RESERVED_NODE) {
if (numberOfActive == 0) {
policy.disabled = true;
// gas refund
policy.sponsor = address(0);
policy.owner = address(0);
policy.feeRate = 0;
policy.startTimestamp = 0;
policy.endTimestamp = 0;
emit PolicyRevoked(_policyId, msg.sender, refundValue);
} else {
emit RefundForPolicy(_policyId, msg.sender, refundValue);
}
} else {
// arrangement not found
require(i < policy.arrangements.length);
}
if (refundValue > 0) {
policySponsor.sendValue(refundValue);
}
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node or RESERVED_NODE if all nodes should be used
*/
function calculateRefundValueInternal(bytes16 _policyId, address _node)
internal view returns (uint256 refundValue)
{
refundValue = 0;
Policy storage policy = policies[_policyId];
require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled);
uint256 i = 0;
for (; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) {
continue;
}
(uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement);
refundValue += nodeRefundValue;
if (_node != RESERVED_NODE) {
break;
}
}
if (_node != RESERVED_NODE) {
// arrangement not found
require(i < policy.arrangements.length);
}
}
/**
* @notice Revoke policy by the sponsor
* @param _policyId Policy id
*/
function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) {
require(getPolicyOwner(_policyId) == msg.sender);
return refundInternal(_policyId, RESERVED_NODE, true);
}
/**
* @notice Revoke arrangement by the sponsor
* @param _policyId Policy id
* @param _node Node that will be excluded
*/
function revokeArrangement(bytes16 _policyId, address _node)
external returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
require(getPolicyOwner(_policyId) == msg.sender);
return refundInternal(_policyId, _node, true);
}
/**
* @notice Get unsigned hash for revocation
* @param _policyId Policy id
* @param _node Node that will be excluded
* @return Revocation hash, EIP191 version 0x45 ('E')
*/
function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) {
return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45));
}
/**
* @notice Check correctness of signature
* @param _policyId Policy id
* @param _node Node that will be excluded, zero address if whole policy will be revoked
* @param _signature Signature of owner
*/
function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view {
bytes32 hash = getRevocationHash(_policyId, _node);
address recovered = SignatureVerifier.recover(hash, _signature);
require(getPolicyOwner(_policyId) == recovered);
}
/**
* @notice Revoke policy or arrangement using owner's signature
* @param _policyId Policy id
* @param _node Node that will be excluded, zero address if whole policy will be revoked
* @param _signature Signature of owner, EIP191 version 0x45 ('E')
*/
function revoke(bytes16 _policyId, address _node, bytes calldata _signature)
external returns (uint256 refundValue)
{
checkOwnerSignature(_policyId, _node, _signature);
return refundInternal(_policyId, _node, true);
}
/**
* @notice Refund part of fee by the sponsor
* @param _policyId Policy id
*/
function refund(bytes16 _policyId) external {
Policy storage policy = policies[_policyId];
require(policy.owner == msg.sender || policy.sponsor == msg.sender);
refundInternal(_policyId, RESERVED_NODE, false);
}
/**
* @notice Refund part of one node's fee by the sponsor
* @param _policyId Policy id
* @param _node Node address
*/
function refund(bytes16 _policyId, address _node)
external returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
Policy storage policy = policies[_policyId];
require(policy.owner == msg.sender || policy.sponsor == msg.sender);
return refundInternal(_policyId, _node, false);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
*/
function calculateRefundValue(bytes16 _policyId)
external view returns (uint256 refundValue)
{
return calculateRefundValueInternal(_policyId, RESERVED_NODE);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node
*/
function calculateRefundValue(bytes16 _policyId, address _node)
external view returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
return calculateRefundValueInternal(_policyId, _node);
}
/**
* @notice Get number of arrangements in the policy
* @param _policyId Policy id
*/
function getArrangementsLength(bytes16 _policyId) external view returns (uint256) {
return policies[_policyId].arrangements.length;
}
/**
* @notice Get information about staker's fee rate
* @param _node Address of staker
* @param _period Period to get fee delta
*/
function getNodeFeeDelta(address _node, uint16 _period)
// TODO "virtual" only for tests, probably will be removed after #1512
public view virtual returns (int256)
{
// TODO remove after upgrade #2579
if (_node == RESERVED_NODE && _period == 11) {
return 55;
}
return nodes[_node].feeDelta[_period];
}
/**
* @notice Return the information about arrangement
*/
function getArrangementInfo(bytes16 _policyId, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released (#1501)
// public view returns (ArrangementInfo)
external view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
ArrangementInfo storage info = policies[_policyId].arrangements[_index];
node = info.node;
indexOfDowntimePeriods = info.indexOfDowntimePeriods;
lastRefundedPeriod = info.lastRefundedPeriod;
}
/**
* @dev Get Policy structure by delegatecall
*/
function delegateGetPolicy(address _target, bytes16 _policyId)
internal returns (Policy memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.policies.selector, 1, bytes32(_policyId), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get ArrangementInfo structure by delegatecall
*/
function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index)
internal returns (ArrangementInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get NodeInfo structure by delegatecall
*/
function delegateGetNodeInfo(address _target, address _node)
internal returns (MemoryNodeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get feeRateRange structure by delegatecall
*/
function delegateGetFeeRateRange(address _target) internal returns (Range memory result) {
bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0);
assembly {
result := memoryAddress
}
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState`
function verifyState(address _testTarget) public override virtual {
super.verifyState(_testTarget);
require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp);
Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget);
require(feeRateRange.min == rangeToCheck.min &&
feeRateRange.defaultValue == rangeToCheck.defaultValue &&
feeRateRange.max == rangeToCheck.max);
Policy storage policy = policies[RESERVED_POLICY_ID];
Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID);
require(policyToCheck.sponsor == policy.sponsor &&
policyToCheck.owner == policy.owner &&
policyToCheck.feeRate == policy.feeRate &&
policyToCheck.startTimestamp == policy.startTimestamp &&
policyToCheck.endTimestamp == policy.endTimestamp &&
policyToCheck.disabled == policy.disabled);
require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) ==
policy.arrangements.length);
if (policy.arrangements.length > 0) {
ArrangementInfo storage arrangement = policy.arrangements[0];
ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo(
_testTarget, RESERVED_POLICY_ID, 0);
require(arrangementToCheck.node == arrangement.node &&
arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods &&
arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod);
}
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE);
require(nodeInfoToCheck.fee == nodeInfo.fee &&
nodeInfoToCheck.feeRate == nodeInfo.feeRate &&
nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod &&
nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate);
require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector,
bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11));
}
/// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade`
function finishUpgrade(address _target) public override virtual {
super.finishUpgrade(_target);
if (resetTimestamp == 0) {
resetTimestamp = uint64(block.timestamp);
}
// Create fake Policy and NodeInfo to use them in verifyState(address)
Policy storage policy = policies[RESERVED_POLICY_ID];
policy.sponsor = msg.sender;
policy.owner = address(this);
policy.startTimestamp = 1;
policy.endTimestamp = 2;
policy.feeRate = 3;
policy.disabled = true;
policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22));
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
nodeInfo.fee = 100;
nodeInfo.feeRate = 33;
nodeInfo.previousFeePeriod = 44;
nodeInfo.feeDelta[11] = 55;
nodeInfo.minFeeRate = 777;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./Upgradeable.sol";
import "../../zeppelin/utils/Address.sol";
/**
* @notice ERC897 - ERC DelegateProxy
*/
interface ERCProxy {
function proxyType() external pure returns (uint256);
function implementation() external view returns (address);
}
/**
* @notice Proxying requests to other contracts.
* Client should use ABI of real contract and address of this contract
*/
contract Dispatcher is Upgradeable, ERCProxy {
using Address for address;
event Upgraded(address indexed from, address indexed to, address owner);
event RolledBack(address indexed from, address indexed to, address owner);
/**
* @dev Set upgrading status before and after operations
*/
modifier upgrading()
{
isUpgrade = UPGRADE_TRUE;
_;
isUpgrade = UPGRADE_FALSE;
}
/**
* @param _target Target contract address
*/
constructor(address _target) upgrading {
require(_target.isContract());
// Checks that target contract inherits Dispatcher state
verifyState(_target);
// `verifyState` must work with its contract
verifyUpgradeableState(_target, _target);
target = _target;
finishUpgrade();
emit Upgraded(address(0), _target, msg.sender);
}
//------------------------ERC897------------------------
/**
* @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() external pure override returns (uint256) {
return 2;
}
/**
* @notice ERC897, gets the address of the implementation where every call will be delegated
*/
function implementation() external view override returns (address) {
return target;
}
//------------------------------------------------------------
/**
* @notice Verify new contract storage and upgrade target
* @param _target New target contract address
*/
function upgrade(address _target) public onlyOwner upgrading {
require(_target.isContract());
// Checks that target contract has "correct" (as much as possible) state layout
verifyState(_target);
//`verifyState` must work with its contract
verifyUpgradeableState(_target, _target);
if (target.isContract()) {
verifyUpgradeableState(target, _target);
}
previousTarget = target;
target = _target;
finishUpgrade();
emit Upgraded(previousTarget, _target, msg.sender);
}
/**
* @notice Rollback to previous target
* @dev Test storage carefully before upgrade again after rollback
*/
function rollback() public onlyOwner upgrading {
require(previousTarget.isContract());
emit RolledBack(target, previousTarget, msg.sender);
// should be always true because layout previousTarget -> target was already checked
// but `verifyState` is not 100% accurate so check again
verifyState(previousTarget);
if (target.isContract()) {
verifyUpgradeableState(previousTarget, target);
}
target = previousTarget;
previousTarget = address(0);
finishUpgrade();
}
/**
* @dev Call verifyState method for Upgradeable contract
*/
function verifyUpgradeableState(address _from, address _to) private {
(bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to));
require(callSuccess);
}
/**
* @dev Call finishUpgrade method from the Upgradeable contract
*/
function finishUpgrade() private {
(bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target));
require(callSuccess);
}
function verifyState(address _testTarget) public override onlyWhileUpgrading {
//checks equivalence accessing state through new contract and current storage
require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner());
require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target);
require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget);
require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade);
}
/**
* @dev Override function using empty code because no reason to call this function in Dispatcher
*/
function finishUpgrade(address) public override {}
/**
* @dev Receive function sends empty request to the target contract
*/
receive() external payable {
assert(target.isContract());
// execute receive function from target contract using storage of the dispatcher
(bool callSuccess,) = target.delegatecall("");
if (!callSuccess) {
revert();
}
}
/**
* @dev Fallback function sends all requests to the target contract
*/
fallback() external payable {
assert(target.isContract());
// execute requested function from target contract using storage of the dispatcher
(bool callSuccess,) = target.delegatecall(msg.data);
if (callSuccess) {
// copy result of the request to the return data
// we can use the second return value from `delegatecall` (bytes memory)
// but it will consume a little more gas
assembly {
returndatacopy(0x0, 0x0, returndatasize())
return(0x0, returndatasize())
}
} else {
revert();
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/utils/Address.sol";
import "../../zeppelin/token/ERC20/SafeERC20.sol";
import "./StakingInterface.sol";
import "../../zeppelin/proxy/Initializable.sol";
/**
* @notice Router for accessing interface contract
*/
contract StakingInterfaceRouter is Ownable {
BaseStakingInterface public target;
/**
* @param _target Address of the interface contract
*/
constructor(BaseStakingInterface _target) {
require(address(_target.token()) != address(0));
target = _target;
}
/**
* @notice Upgrade interface
* @param _target New contract address
*/
function upgrade(BaseStakingInterface _target) external onlyOwner {
require(address(_target.token()) != address(0));
target = _target;
}
}
/**
* @notice Internal base class for AbstractStakingContract and InitializableStakingContract
*/
abstract contract RawStakingContract {
using Address for address;
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view virtual returns (StakingInterfaceRouter);
/**
* @dev Checks permission for calling fallback function
*/
function isFallbackAllowed() public virtual returns (bool);
/**
* @dev Withdraw tokens from staking contract
*/
function withdrawTokens(uint256 _value) public virtual;
/**
* @dev Withdraw ETH from staking contract
*/
function withdrawETH() public virtual;
receive() external payable {}
/**
* @dev Function sends all requests to the target contract
*/
fallback() external payable {
require(isFallbackAllowed());
address target = address(router().target());
require(target.isContract());
// execute requested function from target contract
(bool callSuccess, ) = target.delegatecall(msg.data);
if (callSuccess) {
// copy result of the request to the return data
// we can use the second return value from `delegatecall` (bytes memory)
// but it will consume a little more gas
assembly {
returndatacopy(0x0, 0x0, returndatasize())
return(0x0, returndatasize())
}
} else {
revert();
}
}
}
/**
* @notice Base class for any staking contract (not usable with openzeppelin proxy)
* @dev Implement `isFallbackAllowed()` or override fallback function
* Implement `withdrawTokens(uint256)` and `withdrawETH()` functions
*/
abstract contract AbstractStakingContract is RawStakingContract {
StakingInterfaceRouter immutable router_;
NuCypherToken public immutable token;
/**
* @param _router Interface router contract address
*/
constructor(StakingInterfaceRouter _router) {
router_ = _router;
NuCypherToken localToken = _router.target().token();
require(address(localToken) != address(0));
token = localToken;
}
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view override returns (StakingInterfaceRouter) {
return router_;
}
}
/**
* @notice Base class for any staking contract usable with openzeppelin proxy
* @dev Implement `isFallbackAllowed()` or override fallback function
* Implement `withdrawTokens(uint256)` and `withdrawETH()` functions
*/
abstract contract InitializableStakingContract is Initializable, RawStakingContract {
StakingInterfaceRouter router_;
NuCypherToken public token;
/**
* @param _router Interface router contract address
*/
function initialize(StakingInterfaceRouter _router) public initializer {
router_ = _router;
NuCypherToken localToken = _router.target().token();
require(address(localToken) != address(0));
token = localToken;
}
/**
* @dev Returns address of StakingInterfaceRouter
*/
function router() public view override returns (StakingInterfaceRouter) {
return router_;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "./AbstractStakingContract.sol";
import "../NuCypherToken.sol";
import "../StakingEscrow.sol";
import "../PolicyManager.sol";
import "../WorkLock.sol";
/**
* @notice Base StakingInterface
*/
contract BaseStakingInterface {
address public immutable stakingInterfaceAddress;
NuCypherToken public immutable token;
StakingEscrow public immutable escrow;
PolicyManager public immutable policyManager;
WorkLock public immutable workLock;
/**
* @notice Constructor sets addresses of the contracts
* @param _token Token contract
* @param _escrow Escrow contract
* @param _policyManager PolicyManager contract
* @param _workLock WorkLock contract
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
PolicyManager _policyManager,
WorkLock _workLock
) {
require(_token.totalSupply() > 0 &&
_escrow.secondsPerPeriod() > 0 &&
_policyManager.secondsPerPeriod() > 0 &&
// in case there is no worklock contract
(address(_workLock) == address(0) || _workLock.boostingRefund() > 0));
token = _token;
escrow = _escrow;
policyManager = _policyManager;
workLock = _workLock;
stakingInterfaceAddress = address(this);
}
/**
* @dev Checks executing through delegate call
*/
modifier onlyDelegateCall()
{
require(stakingInterfaceAddress != address(this));
_;
}
/**
* @dev Checks the existence of the worklock contract
*/
modifier workLockSet()
{
require(address(workLock) != address(0));
_;
}
}
/**
* @notice Interface for accessing main contracts from a staking contract
* @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields.
* @dev |v1.7.1|
*/
contract StakingInterface is BaseStakingInterface {
event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods);
event WithdrawnAsStaker(address indexed sender, uint256 value);
event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value);
event LockedAndCreated(address indexed sender, uint256 value, uint16 periods);
event LockedAndIncreased(address indexed sender, uint256 index, uint256 value);
event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods);
event Merged(address indexed sender, uint256 index1, uint256 index2);
event Minted(address indexed sender);
event PolicyFeeWithdrawn(address indexed sender, uint256 value);
event MinFeeRateSet(address indexed sender, uint256 value);
event ReStakeSet(address indexed sender, bool reStake);
event WorkerBonded(address indexed sender, address worker);
event Prolonged(address indexed sender, uint256 index, uint16 periods);
event WindDownSet(address indexed sender, bool windDown);
event SnapshotSet(address indexed sender, bool snapshotsEnabled);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH);
event BidCanceled(address indexed sender);
event CompensationWithdrawn(address indexed sender);
/**
* @notice Constructor sets addresses of the contracts
* @param _token Token contract
* @param _escrow Escrow contract
* @param _policyManager PolicyManager contract
* @param _workLock WorkLock contract
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
PolicyManager _policyManager,
WorkLock _workLock
)
BaseStakingInterface(_token, _escrow, _policyManager, _workLock)
{
}
/**
* @notice Bond worker in the staking escrow
* @param _worker Worker address
*/
function bondWorker(address _worker) public onlyDelegateCall {
escrow.bondWorker(_worker);
emit WorkerBonded(msg.sender, _worker);
}
/**
* @notice Set `reStake` parameter in the staking escrow
* @param _reStake Value for parameter
*/
function setReStake(bool _reStake) public onlyDelegateCall {
escrow.setReStake(_reStake);
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Deposit tokens to the staking escrow
* @param _value Amount of token to deposit
* @param _periods Amount of periods during which tokens will be locked
*/
function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall {
require(token.balanceOf(address(this)) >= _value);
token.approve(address(escrow), _value);
escrow.deposit(address(this), _value, _periods);
emit DepositedAsStaker(msg.sender, _value, _periods);
}
/**
* @notice Deposit tokens to the staking escrow
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall {
require(token.balanceOf(address(this)) >= _value);
token.approve(address(escrow), _value);
escrow.depositAndIncrease(_index, _value);
emit DepositedAndIncreased(msg.sender, _index, _value);
}
/**
* @notice Withdraw available amount of tokens from the staking escrow to the staking contract
* @param _value Amount of token to withdraw
*/
function withdrawAsStaker(uint256 _value) public onlyDelegateCall {
escrow.withdraw(_value);
emit WithdrawnAsStaker(msg.sender, _value);
}
/**
* @notice Lock some tokens in the staking escrow
* @param _value Amount of tokens which should lock
* @param _periods Amount of periods during which tokens will be locked
*/
function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall {
escrow.lockAndCreate(_value, _periods);
emit LockedAndCreated(msg.sender, _value, _periods);
}
/**
* @notice Lock some tokens in the staking escrow
* @param _index Index of the sub-stake
* @param _value Amount of tokens which will be locked
*/
function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall {
escrow.lockAndIncrease(_index, _value);
emit LockedAndIncreased(msg.sender, _index, _value);
}
/**
* @notice Divide stake into two parts
* @param _index Index of stake
* @param _newValue New stake value
* @param _periods Amount of periods for extending stake
*/
function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall {
escrow.divideStake(_index, _newValue, _periods);
emit Divided(msg.sender, _index, _newValue, _periods);
}
/**
* @notice Merge two sub-stakes into one
* @param _index1 Index of the first sub-stake
* @param _index2 Index of the second sub-stake
*/
function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall {
escrow.mergeStake(_index1, _index2);
emit Merged(msg.sender, _index1, _index2);
}
/**
* @notice Mint tokens in the staking escrow
*/
function mint() public onlyDelegateCall {
escrow.mint();
emit Minted(msg.sender);
}
/**
* @notice Withdraw available policy fees from the policy manager to the staking contract
*/
function withdrawPolicyFee() public onlyDelegateCall {
uint256 value = policyManager.withdraw();
emit PolicyFeeWithdrawn(msg.sender, value);
}
/**
* @notice Set the minimum fee that the staker will accept in the policy manager contract
*/
function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall {
policyManager.setMinFeeRate(_minFeeRate);
emit MinFeeRateSet(msg.sender, _minFeeRate);
}
/**
* @notice Prolong active sub stake
* @param _index Index of the sub stake
* @param _periods Amount of periods for extending sub stake
*/
function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall {
escrow.prolongStake(_index, _periods);
emit Prolonged(msg.sender, _index, _periods);
}
/**
* @notice Set `windDown` parameter in the staking escrow
* @param _windDown Value for parameter
*/
function setWindDown(bool _windDown) public onlyDelegateCall {
escrow.setWindDown(_windDown);
emit WindDownSet(msg.sender, _windDown);
}
/**
* @notice Set `snapshots` parameter in the staking escrow
* @param _enableSnapshots Value for parameter
*/
function setSnapshots(bool _enableSnapshots) public onlyDelegateCall {
escrow.setSnapshots(_enableSnapshots);
emit SnapshotSet(msg.sender, _enableSnapshots);
}
/**
* @notice Bid for tokens by transferring ETH
*/
function bid(uint256 _value) public payable onlyDelegateCall workLockSet {
workLock.bid{value: _value}();
emit Bid(msg.sender, _value);
}
/**
* @notice Cancel bid and refund deposited ETH
*/
function cancelBid() public onlyDelegateCall workLockSet {
workLock.cancelBid();
emit BidCanceled(msg.sender);
}
/**
* @notice Withdraw compensation after force refund
*/
function withdrawCompensation() public onlyDelegateCall workLockSet {
workLock.withdrawCompensation();
emit CompensationWithdrawn(msg.sender);
}
/**
* @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract
*/
function claim() public onlyDelegateCall workLockSet {
uint256 claimedTokens = workLock.claim();
emit Claimed(msg.sender, claimedTokens);
}
/**
* @notice Refund ETH for the completed work
*/
function refund() public onlyDelegateCall workLockSet {
uint256 refundETH = workLock.refund();
emit Refund(msg.sender, refundETH);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/token/ERC20/SafeERC20.sol";
import "../zeppelin/utils/Address.sol";
import "../zeppelin/ownership/Ownable.sol";
import "./NuCypherToken.sol";
import "./StakingEscrow.sol";
import "./lib/AdditionalMath.sol";
/**
* @notice The WorkLock distribution contract
*/
contract WorkLock is Ownable {
using SafeERC20 for NuCypherToken;
using SafeMath for uint256;
using AdditionalMath for uint256;
using Address for address payable;
using Address for address;
event Deposited(address indexed sender, uint256 value);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH, uint256 completedWork);
event Canceled(address indexed sender, uint256 value);
event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex);
event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH);
event CompensationWithdrawn(address indexed sender, uint256 value);
event Shutdown(address indexed sender);
struct WorkInfo {
uint256 depositedETH;
uint256 completedWork;
bool claimed;
uint128 index;
}
uint16 public constant SLOWING_REFUND = 100;
uint256 private constant MAX_ETH_SUPPLY = 2e10 ether;
NuCypherToken public immutable token;
StakingEscrow public immutable escrow;
/*
* @dev WorkLock calculations:
* bid = minBid + bonusETHPart
* bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens
* bonusDepositRate = bonusTokenSupply / bonusETHSupply
* claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate
* bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund
* refundETH = completedWork / refundRate
*/
uint256 public immutable boostingRefund;
uint256 public immutable minAllowedBid;
uint16 public immutable stakingPeriods;
// copy from the escrow contract
uint256 public immutable maxAllowableLockedTokens;
uint256 public immutable minAllowableLockedTokens;
uint256 public tokenSupply;
uint256 public startBidDate;
uint256 public endBidDate;
uint256 public endCancellationDate;
uint256 public bonusETHSupply;
mapping(address => WorkInfo) public workInfo;
mapping(address => uint256) public compensation;
address[] public bidders;
// if value == bidders.length then WorkLock is fully checked
uint256 public nextBidderToCheck;
/**
* @dev Checks timestamp regarding cancellation window
*/
modifier afterCancellationWindow()
{
require(block.timestamp >= endCancellationDate,
"Operation is allowed when cancellation phase is over");
_;
}
/**
* @param _token Token contract
* @param _escrow Escrow contract
* @param _startBidDate Timestamp when bidding starts
* @param _endBidDate Timestamp when bidding will end
* @param _endCancellationDate Timestamp when cancellation will ends
* @param _boostingRefund Coefficient to boost refund ETH
* @param _stakingPeriods Amount of periods during which tokens will be locked after claiming
* @param _minAllowedBid Minimum allowed ETH amount for bidding
*/
constructor(
NuCypherToken _token,
StakingEscrow _escrow,
uint256 _startBidDate,
uint256 _endBidDate,
uint256 _endCancellationDate,
uint256 _boostingRefund,
uint16 _stakingPeriods,
uint256 _minAllowedBid
) {
uint256 totalSupply = _token.totalSupply();
require(totalSupply > 0 && // token contract is deployed and accessible
_escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible
_escrow.token() == _token && // same token address for worklock and escrow
_endBidDate > _startBidDate && // bidding period lasts some time
_endBidDate > block.timestamp && // there is time to make a bid
_endCancellationDate >= _endBidDate && // cancellation window includes bidding
_minAllowedBid > 0 && // min allowed bid was set
_boostingRefund > 0 && // boosting coefficient was set
_stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract
// worst case for `ethToWork()` and `workToETH()`,
// when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply
require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND &&
MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund);
token = _token;
escrow = _escrow;
startBidDate = _startBidDate;
endBidDate = _endBidDate;
endCancellationDate = _endCancellationDate;
boostingRefund = _boostingRefund;
stakingPeriods = _stakingPeriods;
minAllowedBid = _minAllowedBid;
maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens();
minAllowableLockedTokens = _escrow.minAllowableLockedTokens();
}
/**
* @notice Deposit tokens to contract
* @param _value Amount of tokens to transfer
*/
function tokenDeposit(uint256 _value) external {
require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding");
token.safeTransferFrom(msg.sender, address(this), _value);
tokenSupply += _value;
emit Deposited(msg.sender, _value);
}
/**
* @notice Calculate amount of tokens that will be get for specified amount of ETH
* @dev This value will be fixed only after end of bidding
*/
function ethToTokens(uint256 _ethAmount) public view returns (uint256) {
if (_ethAmount < minAllowedBid) {
return 0;
}
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return tokenSupply / bidders.length;
}
uint256 bonusETH = _ethAmount - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply);
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
*/
function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply)
internal view returns (uint256)
{
return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund));
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
* @dev This value will be fixed only after end of bidding
* @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work
* @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted
* @dev _ethToReclaim + _restOfDepositedETH = depositedETH
*/
function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) {
uint256 baseETHSupply = bidders.length * minAllowedBid;
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply);
}
uint256 baseETH = 0;
uint256 bonusETH = 0;
// If the staker's total remaining deposit (including the specified sum of ETH to reclaim)
// is lower than the minimum bid size,
// then only the base part is used to calculate the work required to reclaim ETH
if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) {
baseETH = _ethToReclaim;
// If the staker's remaining deposit (not including the specified sum of ETH to reclaim)
// is still greater than the minimum bid size,
// then only the bonus part is used to calculate the work required to reclaim ETH
} else if (_restOfDepositedETH >= minAllowedBid) {
bonusETH = _ethToReclaim;
// If the staker's remaining deposit (not including the specified sum of ETH to reclaim)
// is lower than the minimum bid size,
// then both the base and bonus parts must be used to calculate the work required to reclaim ETH
} else {
bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid;
baseETH = _ethToReclaim - bonusETH;
}
uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens;
uint256 work = 0;
if (baseETH > 0) {
work = ethToWork(baseETH, baseTokenSupply, baseETHSupply);
}
if (bonusETH > 0) {
uint256 bonusTokenSupply = tokenSupply - baseTokenSupply;
work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply);
}
return work;
}
/**
* @notice Calculate amount of work that need to be done to refund specified amount of ETH
* @dev This value will be fixed only after end of bidding
*/
function ethToWork(uint256 _ethAmount) public view returns (uint256) {
return ethToWork(_ethAmount, 0);
}
/**
* @notice Calculate amount of ETH that will be refund for completing specified amount of work
*/
function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply)
internal view returns (uint256)
{
return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND));
}
/**
* @notice Calculate amount of ETH that will be refund for completing specified amount of work
* @dev This value will be fixed only after end of bidding
*/
function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) {
uint256 baseETHSupply = bidders.length * minAllowedBid;
// when all participants bid with the same minimum amount of eth
if (bonusETHSupply == 0) {
return workToETH(_completedWork, baseETHSupply, tokenSupply);
}
uint256 bonusWork = 0;
uint256 bonusETH = 0;
uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens;
if (_depositedETH > minAllowedBid) {
bonusETH = _depositedETH - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - baseTokenSupply;
bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply);
if (_completedWork <= bonusWork) {
return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply);
}
}
_completedWork -= bonusWork;
return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply);
}
/**
* @notice Get remaining work to full refund
*/
function getRemainingWork(address _bidder) external view returns (uint256) {
WorkInfo storage info = workInfo[_bidder];
uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork);
uint256 remainingWork = ethToWork(info.depositedETH);
if (remainingWork <= completedWork) {
return 0;
}
return remainingWork - completedWork;
}
/**
* @notice Get length of bidders array
*/
function getBiddersLength() external view returns (uint256) {
return bidders.length;
}
/**
* @notice Bid for tokens by transferring ETH
*/
function bid() external payable {
require(block.timestamp >= startBidDate, "Bidding is not open yet");
require(block.timestamp < endBidDate, "Bidding is already finished");
WorkInfo storage info = workInfo[msg.sender];
// first bid
if (info.depositedETH == 0) {
require(msg.value >= minAllowedBid, "Bid must be at least minimum");
require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders");
info.index = uint128(bidders.length);
bidders.push(msg.sender);
bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid);
} else {
bonusETHSupply = bonusETHSupply.add(msg.value);
}
info.depositedETH = info.depositedETH.add(msg.value);
emit Bid(msg.sender, msg.value);
}
/**
* @notice Cancel bid and refund deposited ETH
*/
function cancelBid() external {
require(block.timestamp < endCancellationDate,
"Cancellation allowed only during cancellation window");
WorkInfo storage info = workInfo[msg.sender];
require(info.depositedETH > 0, "No bid to cancel");
require(!info.claimed, "Tokens are already claimed");
uint256 refundETH = info.depositedETH;
info.depositedETH = 0;
// remove from bidders array, move last bidder to the empty place
uint256 lastIndex = bidders.length - 1;
if (info.index != lastIndex) {
address lastBidder = bidders[lastIndex];
bidders[info.index] = lastBidder;
workInfo[lastBidder].index = info.index;
}
bidders.pop();
if (refundETH > minAllowedBid) {
bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid);
}
msg.sender.sendValue(refundETH);
emit Canceled(msg.sender, refundETH);
}
/**
* @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens
*/
function shutdown() external onlyOwner {
require(!isClaimingAvailable(), "Claiming has already been enabled");
internalShutdown();
}
/**
* @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens
*/
function internalShutdown() internal {
startBidDate = 0;
endBidDate = 0;
endCancellationDate = uint256(0) - 1; // "infinite" cancellation window
token.safeTransfer(owner(), tokenSupply);
emit Shutdown(msg.sender);
}
/**
* @notice Make force refund to bidders who can get tokens more than maximum allowed
* @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund
*/
function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow {
require(nextBidderToCheck != bidders.length, "Bidders have already been checked");
uint256 length = _biddersForRefund.length;
require(length > 0, "Must be at least one bidder for a refund");
uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens);
if (bidders.length < minNumberOfBidders) {
internalShutdown();
return;
}
address previousBidder = _biddersForRefund[0];
uint256 minBid = workInfo[previousBidder].depositedETH;
uint256 maxBid = minBid;
// get minimum and maximum bids
for (uint256 i = 1; i < length; i++) {
address bidder = _biddersForRefund[i];
uint256 depositedETH = workInfo[bidder].depositedETH;
require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders");
if (minBid > depositedETH) {
minBid = depositedETH;
} else if (maxBid < depositedETH) {
maxBid = depositedETH;
}
previousBidder = bidder;
}
uint256[] memory refunds = new uint256[](length);
// first step - align at a minimum bid
if (minBid != maxBid) {
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
WorkInfo storage info = workInfo[bidder];
if (info.depositedETH > minBid) {
refunds[i] = info.depositedETH - minBid;
info.depositedETH = minBid;
bonusETHSupply -= refunds[i];
}
}
}
require(ethToTokens(minBid) > maxAllowableLockedTokens,
"At least one of bidders has allowable bid");
// final bids adjustment (only for bonus part)
// (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales)
uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens;
uint256 minBonusETH = minBid - minAllowedBid;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
uint256 refundETH = minBonusETH.mul(bonusTokenSupply)
.sub(maxBonusTokens.mul(bonusETHSupply))
.divCeil(bonusTokenSupply - maxBonusTokens.mul(length));
uint256 resultBid = minBid.sub(refundETH);
bonusETHSupply -= length * refundETH;
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
WorkInfo storage info = workInfo[bidder];
refunds[i] += refundETH;
info.depositedETH = resultBid;
}
// reset verification
nextBidderToCheck = 0;
// save a refund
for (uint256 i = 0; i < length; i++) {
address bidder = _biddersForRefund[i];
compensation[bidder] += refunds[i];
emit ForceRefund(msg.sender, bidder, refunds[i]);
}
}
/**
* @notice Withdraw compensation after force refund
*/
function withdrawCompensation() external {
uint256 refund = compensation[msg.sender];
require(refund > 0, "There is no compensation");
compensation[msg.sender] = 0;
msg.sender.sendValue(refund);
emit CompensationWithdrawn(msg.sender, refund);
}
/**
* @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants,
* starting from the last point `nextBidderToCheck`
* @dev Method stops working when the remaining gas is less than `_gasToSaveState`
* and saves the state in `nextBidderToCheck`.
* If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array
*/
function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) {
require(nextBidderToCheck != bidders.length, "Bidders have already been checked");
// all participants bid with the same minimum amount of eth
uint256 index = nextBidderToCheck;
if (bonusETHSupply == 0) {
require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders");
index = bidders.length;
}
uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens;
uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens;
uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply);
while (index < bidders.length && gasleft() > _gasToSaveState) {
address bidder = bidders[index];
require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid");
index++;
}
if (index != nextBidderToCheck) {
emit BiddersChecked(msg.sender, nextBidderToCheck, index);
nextBidderToCheck = index;
}
return nextBidderToCheck;
}
/**
* @notice Checks if claiming available
*/
function isClaimingAvailable() public view returns (bool) {
return block.timestamp >= endCancellationDate &&
nextBidderToCheck == bidders.length;
}
/**
* @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract.
*/
function claim() external returns (uint256 claimedTokens) {
require(isClaimingAvailable(), "Claiming has not been enabled yet");
WorkInfo storage info = workInfo[msg.sender];
require(!info.claimed, "Tokens are already claimed");
claimedTokens = ethToTokens(info.depositedETH);
require(claimedTokens > 0, "Nothing to claim");
info.claimed = true;
token.approve(address(escrow), claimedTokens);
escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods);
info.completedWork = escrow.setWorkMeasurement(msg.sender, true);
emit Claimed(msg.sender, claimedTokens);
}
/**
* @notice Get available refund for bidder
*/
function getAvailableRefund(address _bidder) public view returns (uint256) {
WorkInfo storage info = workInfo[_bidder];
// nothing to refund
if (info.depositedETH == 0) {
return 0;
}
uint256 currentWork = escrow.getCompletedWork(_bidder);
uint256 completedWork = currentWork.sub(info.completedWork);
// no work that has been completed since last refund
if (completedWork == 0) {
return 0;
}
uint256 refundETH = workToETH(completedWork, info.depositedETH);
if (refundETH > info.depositedETH) {
refundETH = info.depositedETH;
}
return refundETH;
}
/**
* @notice Refund ETH for the completed work
*/
function refund() external returns (uint256 refundETH) {
WorkInfo storage info = workInfo[msg.sender];
require(info.claimed, "Tokens must be claimed before refund");
refundETH = getAvailableRefund(msg.sender);
require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work");
if (refundETH == info.depositedETH) {
escrow.setWorkMeasurement(msg.sender, false);
}
info.depositedETH = info.depositedETH.sub(refundETH);
// convert refund back to work to eliminate potential rounding errors
uint256 completedWork = ethToWork(refundETH, info.depositedETH);
info.completedWork = info.completedWork.add(completedWork);
emit Refund(msg.sender, refundETH, completedWork);
msg.sender.sendValue(refundETH);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers and owner
**/
contract PoolingStakingContract is AbstractStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens);
event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens);
event ETHWithdrawn(address indexed sender, uint256 value);
event DepositSet(address indexed sender, bool value);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
}
StakingEscrow public immutable escrow;
uint256 public totalDepositedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 public ownerFraction;
uint256 public ownerWithdrawnReward;
uint256 public ownerWithdrawnETH;
mapping (address => Delegator) public delegators;
bool depositIsEnabled = true;
/**
* @param _router Address of the StakingInterfaceRouter contract
* @param _ownerFraction Base owner's portion of reward
*/
constructor(
StakingInterfaceRouter _router,
uint256 _ownerFraction
)
AbstractStakingContract(_router)
{
escrow = _router.target().escrow();
ownerFraction = _ownerFraction;
}
/**
* @notice Enabled deposit
*/
function enableDeposit() external onlyOwner {
depositIsEnabled = true;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Disable deposit
*/
function disableDeposit() external onlyOwner {
depositIsEnabled = false;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(depositIsEnabled, "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens += _value;
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
uint256 stakedTokens = escrow.getAllTokens(address(this));
uint256 freeTokens = token.balanceOf(address(this));
uint256 reward = stakedTokens + freeTokens - totalDepositedTokens;
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for pool owner
*/
function getAvailableOwnerReward() public view returns (uint256) {
uint256 reward = getCumulativeReward();
uint256 maxAllowableReward;
if (totalDepositedTokens != 0) {
maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction));
} else {
maxAllowableReward = reward;
}
return maxAllowableReward.sub(ownerWithdrawnReward);
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableReward(address _delegator) public view returns (uint256) {
if (totalDepositedTokens == 0) {
return 0;
}
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens)
.div(totalDepositedTokens.add(ownerFraction));
return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0;
}
/**
* @notice Withdraw reward in tokens to owner
*/
function withdrawOwnerReward() public onlyOwner {
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableOwnerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(availableReward > 0, "There is no available reward to withdraw");
ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw amount of tokens to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
uint256 availableReward = getAvailableReward(msg.sender);
Delegator storage delegator = delegators[msg.sender];
require(_value <= availableReward + delegator.depositedTokens,
"Requested amount of tokens exceeded allowed portion");
if (_value <= availableReward) {
delegator.withdrawnReward += _value;
totalWithdrawnReward += _value;
} else {
delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
uint256 depositToWithdraw = _value - availableReward;
uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw;
uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens);
uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens);
totalDepositedTokens -= depositToWithdraw;
totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward);
totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH);
delegator.depositedTokens = newDepositedTokens;
delegator.withdrawnReward = newWithdrawnReward;
delegator.withdrawnETH = newWithdrawnETH;
}
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available ether for owner
*/
function getAvailableOwnerETH() public view returns (uint256) {
// TODO boilerplate code
uint256 balance = address(this).balance;
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction));
uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Get available ether for delegator
*/
function getAvailableETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
// TODO boilerplate code
uint256 balance = address(this).balance;
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens)
.div(totalDepositedTokens.add(ownerFraction));
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to pool owner
*/
function withdrawOwnerETH() public onlyOwner {
uint256 availableETH = getAvailableOwnerETH();
require(availableETH > 0, "There is no available ETH to withdraw");
ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
uint256 availableETH = getAvailableETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
Delegator storage delegator = delegators[msg.sender];
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
**/
function isFallbackAllowed() public view override returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers
**/
contract PoolingStakingContractV2 is InitializableStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event TokensWithdrawn(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event ETHWithdrawn(address indexed sender, uint256 value);
event WorkerOwnerSet(address indexed sender, address indexed workerOwner);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
}
/**
* Defines base fraction and precision of worker fraction.
* E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000)
*/
uint256 public constant BASIS_FRACTION = 10000;
StakingEscrow public escrow;
address public workerOwner;
uint256 public totalDepositedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 workerFraction;
uint256 public workerWithdrawnReward;
mapping(address => Delegator) public delegators;
/**
* @notice Initialize function for using with OpenZeppelin proxy
* @param _workerFraction Share of token reward that worker node owner will get.
* Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission.
* For example, 100 worker fraction is 1% of reward
* @param _router StakingInterfaceRouter address
* @param _workerOwner Owner of worker node, only this address can withdraw worker commission
*/
function initialize(
uint256 _workerFraction,
StakingInterfaceRouter _router,
address _workerOwner
) external initializer {
require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION);
InitializableStakingContract.initialize(_router);
_transferOwnership(msg.sender);
escrow = _router.target().escrow();
workerFraction = _workerFraction;
workerOwner = _workerOwner;
emit WorkerOwnerSet(msg.sender, _workerOwner);
}
/**
* @notice withdrawAll() is allowed
*/
function isWithdrawAllAllowed() public view returns (bool) {
// no tokens in StakingEscrow contract which belong to pool
return escrow.getAllTokens(address(this)) == 0;
}
/**
* @notice deposit() is allowed
*/
function isDepositAllowed() public view returns (bool) {
// tokens which directly belong to pool
uint256 freeTokens = token.balanceOf(address(this));
// no sub-stakes and no earned reward
return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens;
}
/**
* @notice Set worker owner address
*/
function setWorkerOwner(address _workerOwner) external onlyOwner {
workerOwner = _workerOwner;
emit WorkerOwnerSet(msg.sender, _workerOwner);
}
/**
* @notice Calculate worker's fraction depending on deposited tokens
* Override to implement dynamic worker fraction.
*/
function getWorkerFraction() public view virtual returns (uint256) {
return workerFraction;
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(isDepositAllowed(), "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens = delegator.depositedTokens.add(_value);
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
// locked + unlocked tokens in StakingEscrow contract which belong to pool
uint256 stakedTokens = escrow.getAllTokens(address(this));
// tokens which directly belong to pool
uint256 freeTokens = token.balanceOf(address(this));
// tokens in excess of the initially deposited
uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens);
// check how many of reward tokens belong directly to pool
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward.
* Available and withdrawn reward together to use in delegator/owner reward calculations
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for worker node owner
*/
function getAvailableWorkerReward() public view returns (uint256) {
// total current and historical reward
uint256 reward = getCumulativeReward();
// calculate total reward for worker including historical reward
uint256 maxAllowableReward;
// usual case
if (totalDepositedTokens != 0) {
uint256 fraction = getWorkerFraction();
maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION);
// special case when there are no delegators
} else {
maxAllowableReward = reward;
}
// check that worker has any new reward
if (maxAllowableReward > workerWithdrawnReward) {
return maxAllowableReward - workerWithdrawnReward;
}
return 0;
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableDelegatorReward(address _delegator) public view returns (uint256) {
// special case when there are no delegators
if (totalDepositedTokens == 0) {
return 0;
}
// total current and historical reward
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 fraction = getWorkerFraction();
// calculate total reward for delegator including historical reward
// excluding worker share
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div(
totalDepositedTokens.mul(BASIS_FRACTION)
);
// check that worker has any new reward
if (maxAllowableReward > delegator.withdrawnReward) {
return maxAllowableReward - delegator.withdrawnReward;
}
return 0;
}
/**
* @notice Withdraw reward in tokens to worker node owner
*/
function withdrawWorkerReward() external {
require(msg.sender == workerOwner);
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableWorkerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(
availableReward > 0,
"There is no available reward to withdraw"
);
workerWithdrawnReward = workerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw reward to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
Delegator storage delegator = delegators[msg.sender];
uint256 availableReward = getAvailableDelegatorReward(msg.sender);
require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion");
delegator.withdrawnReward = delegator.withdrawnReward.add(_value);
totalWithdrawnReward = totalWithdrawnReward.add(_value);
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Withdraw reward, deposit and fee to delegator
*/
function withdrawAll() public {
require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled");
uint256 balance = token.balanceOf(address(this));
Delegator storage delegator = delegators[msg.sender];
uint256 availableReward = getAvailableDelegatorReward(msg.sender);
uint256 value = availableReward.add(delegator.depositedTokens);
require(value <= balance, "Not enough tokens in the contract");
// TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts
uint256 availableWorkerReward = getAvailableWorkerReward();
// potentially could be less then due reward
uint256 availableETH = getAvailableDelegatorETH(msg.sender);
// prevent losing reward for worker after calculations
uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
if (workerReward > 0) {
require(value.add(workerReward) <= balance, "Not enough tokens in the contract");
token.safeTransfer(workerOwner, workerReward);
emit TokensWithdrawn(workerOwner, workerReward, 0);
}
uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease);
totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward);
totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens);
delegator.withdrawnReward = 0;
delegator.depositedTokens = 0;
token.safeTransfer(msg.sender, value);
emit TokensWithdrawn(msg.sender, value, 0);
totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH);
delegator.withdrawnETH = 0;
if (availableETH > 0) {
emit ETHWithdrawn(msg.sender, availableETH);
msg.sender.sendValue(availableETH);
}
}
/**
* @notice Get available ether for delegator
*/
function getAvailableDelegatorETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 balance = address(this).balance;
// ETH balance + already withdrawn
balance = balance.add(totalWithdrawnETH);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens);
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
Delegator storage delegator = delegators[msg.sender];
uint256 availableETH = getAvailableDelegatorETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
msg.sender.sendValue(availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public override view returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract holds tokens for vesting.
* Also tokens can be used as a stake in the staking escrow contract
*/
contract PreallocationEscrow is AbstractStakingContract, Ownable {
using SafeMath for uint256;
using SafeERC20 for NuCypherToken;
using Address for address payable;
event TokensDeposited(address indexed sender, uint256 value, uint256 duration);
event TokensWithdrawn(address indexed owner, uint256 value);
event ETHWithdrawn(address indexed owner, uint256 value);
StakingEscrow public immutable stakingEscrow;
uint256 public lockedValue;
uint256 public endLockTimestamp;
/**
* @param _router Address of the StakingInterfaceRouter contract
*/
constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) {
stakingEscrow = _router.target().escrow();
}
/**
* @notice Initial tokens deposit
* @param _sender Token sender
* @param _value Amount of token to deposit
* @param _duration Duration of tokens locking
*/
function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal {
require(lockedValue == 0 && _value > 0);
endLockTimestamp = block.timestamp.add(_duration);
lockedValue = _value;
token.safeTransferFrom(_sender, address(this), _value);
emit TokensDeposited(_sender, _value, _duration);
}
/**
* @notice Initial tokens deposit
* @param _value Amount of token to deposit
* @param _duration Duration of tokens locking
*/
function initialDeposit(uint256 _value, uint256 _duration) external {
initialDeposit(msg.sender, _value, _duration);
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Initial tokens deposit
* @param _from Sender
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of seconds during which tokens will be locked
*/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes calldata /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// Copy first 32 bytes from _extraData, according to calldata memory layout:
//
// 0x00: method signature 4 bytes
// 0x04: _from 32 bytes after encoding
// 0x24: _value 32 bytes after encoding
// 0x44: _tokenContract 32 bytes after encoding
// 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter)
// 0x84: _extraData length 32 bytes
// 0xA4: _extraData data Length determined by previous variable
//
// See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
initialDeposit(_from, _value, payload);
}
/**
* @notice Get locked tokens value
*/
function getLockedTokens() public view returns (uint256) {
if (endLockTimestamp <= block.timestamp) {
return 0;
}
return lockedValue;
}
/**
* @notice Withdraw available amount of tokens to owner
* @param _value Amount of token to withdraw
*/
function withdrawTokens(uint256 _value) public override onlyOwner {
uint256 balance = token.balanceOf(address(this));
require(balance >= _value);
// Withdrawal invariant for PreallocationEscrow:
// After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount
require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens());
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value);
}
/**
* @notice Withdraw available ETH to the owner
*/
function withdrawETH() public override onlyOwner {
uint256 balance = address(this).balance;
require(balance != 0);
msg.sender.sendValue(balance);
emit ETHWithdrawn(msg.sender, balance);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public view override returns (bool) {
return msg.sender == owner();
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.7.0;
import "../../zeppelin/ownership/Ownable.sol";
import "../../zeppelin/math/SafeMath.sol";
import "./AbstractStakingContract.sol";
/**
* @notice Contract acts as delegate for sub-stakers and owner
* @author @vzotova and @roma_k
**/
contract WorkLockPoolingContract is InitializableStakingContract, Ownable {
using SafeMath for uint256;
using Address for address payable;
using SafeERC20 for NuCypherToken;
event TokensDeposited(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event TokensWithdrawn(
address indexed sender,
uint256 value,
uint256 depositedTokens
);
event ETHWithdrawn(address indexed sender, uint256 value);
event DepositSet(address indexed sender, bool value);
event Bid(address indexed sender, uint256 depositedETH);
event Claimed(address indexed sender, uint256 claimedTokens);
event Refund(address indexed sender, uint256 refundETH);
struct Delegator {
uint256 depositedTokens;
uint256 withdrawnReward;
uint256 withdrawnETH;
uint256 depositedETHWorkLock;
uint256 refundedETHWorkLock;
bool claimedWorkLockTokens;
}
uint256 public constant BASIS_FRACTION = 100;
StakingEscrow public escrow;
WorkLock public workLock;
address public workerOwner;
uint256 public totalDepositedTokens;
uint256 public workLockClaimedTokens;
uint256 public totalWithdrawnReward;
uint256 public totalWithdrawnETH;
uint256 public totalWorkLockETHReceived;
uint256 public totalWorkLockETHRefunded;
uint256 public totalWorkLockETHWithdrawn;
uint256 workerFraction;
uint256 public workerWithdrawnReward;
mapping(address => Delegator) public delegators;
bool depositIsEnabled = true;
/**
* @notice Initialize function for using with OpenZeppelin proxy
* @param _workerFraction Share of token reward that worker node owner will get.
* Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission
* @param _router StakingInterfaceRouter address
* @param _workerOwner Owner of worker node, only this address can withdraw worker commission
*/
function initialize(
uint256 _workerFraction,
StakingInterfaceRouter _router,
address _workerOwner
) public initializer {
require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION);
InitializableStakingContract.initialize(_router);
_transferOwnership(msg.sender);
escrow = _router.target().escrow();
workLock = _router.target().workLock();
workerFraction = _workerFraction;
workerOwner = _workerOwner;
}
/**
* @notice Enabled deposit
*/
function enableDeposit() external onlyOwner {
depositIsEnabled = true;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Disable deposit
*/
function disableDeposit() external onlyOwner {
depositIsEnabled = false;
emit DepositSet(msg.sender, depositIsEnabled);
}
/**
* @notice Calculate worker's fraction depending on deposited tokens
*/
function getWorkerFraction() public view returns (uint256) {
return workerFraction;
}
/**
* @notice Transfer tokens as delegator
* @param _value Amount of tokens to transfer
*/
function depositTokens(uint256 _value) external {
require(depositIsEnabled, "Deposit must be enabled");
require(_value > 0, "Value must be not empty");
totalDepositedTokens = totalDepositedTokens.add(_value);
Delegator storage delegator = delegators[msg.sender];
delegator.depositedTokens = delegator.depositedTokens.add(_value);
token.safeTransferFrom(msg.sender, address(this), _value);
emit TokensDeposited(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Delegator can transfer ETH directly to workLock
*/
function escrowETH() external payable {
Delegator storage delegator = delegators[msg.sender];
delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value);
totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value);
workLock.bid{value: msg.value}();
emit Bid(msg.sender, msg.value);
}
/**
* @dev Hide method from StakingInterface
*/
function bid(uint256) public payable {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function withdrawCompensation() public pure {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function cancelBid() public pure {
revert();
}
/**
* @dev Hide method from StakingInterface
*/
function claim() public pure {
revert();
}
/**
* @notice Claim tokens in WorkLock and save number of claimed tokens
*/
function claimTokensFromWorkLock() public {
workLockClaimedTokens = workLock.claim();
totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens);
emit Claimed(address(this), workLockClaimedTokens);
}
/**
* @notice Calculate and save number of claimed tokens for specified delegator
*/
function calculateAndSaveTokensAmount() external {
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
}
/**
* @notice Calculate and save number of claimed tokens for specified delegator
*/
function calculateAndSaveTokensAmount(Delegator storage _delegator) internal {
if (workLockClaimedTokens == 0 ||
_delegator.depositedETHWorkLock == 0 ||
_delegator.claimedWorkLockTokens)
{
return;
}
uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens)
.div(totalWorkLockETHReceived);
_delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare);
_delegator.claimedWorkLockTokens = true;
emit Claimed(msg.sender, delegatorTokensShare);
}
/**
* @notice Get available reward for all delegators and owner
*/
function getAvailableReward() public view returns (uint256) {
uint256 stakedTokens = escrow.getAllTokens(address(this));
uint256 freeTokens = token.balanceOf(address(this));
uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens);
if (reward > freeTokens) {
return freeTokens;
}
return reward;
}
/**
* @notice Get cumulative reward
*/
function getCumulativeReward() public view returns (uint256) {
return getAvailableReward().add(totalWithdrawnReward);
}
/**
* @notice Get available reward in tokens for worker node owner
*/
function getAvailableWorkerReward() public view returns (uint256) {
uint256 reward = getCumulativeReward();
uint256 maxAllowableReward;
if (totalDepositedTokens != 0) {
uint256 fraction = getWorkerFraction();
maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION);
} else {
maxAllowableReward = reward;
}
if (maxAllowableReward > workerWithdrawnReward) {
return maxAllowableReward - workerWithdrawnReward;
}
return 0;
}
/**
* @notice Get available reward in tokens for delegator
*/
function getAvailableReward(address _delegator)
public
view
returns (uint256)
{
if (totalDepositedTokens == 0) {
return 0;
}
uint256 reward = getCumulativeReward();
Delegator storage delegator = delegators[_delegator];
uint256 fraction = getWorkerFraction();
uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div(
totalDepositedTokens.mul(BASIS_FRACTION)
);
return
maxAllowableReward > delegator.withdrawnReward
? maxAllowableReward - delegator.withdrawnReward
: 0;
}
/**
* @notice Withdraw reward in tokens to worker node owner
*/
function withdrawWorkerReward() external {
require(msg.sender == workerOwner);
uint256 balance = token.balanceOf(address(this));
uint256 availableReward = getAvailableWorkerReward();
if (availableReward > balance) {
availableReward = balance;
}
require(
availableReward > 0,
"There is no available reward to withdraw"
);
workerWithdrawnReward = workerWithdrawnReward.add(availableReward);
totalWithdrawnReward = totalWithdrawnReward.add(availableReward);
token.safeTransfer(msg.sender, availableReward);
emit TokensWithdrawn(msg.sender, availableReward, 0);
}
/**
* @notice Withdraw reward to delegator
* @param _value Amount of tokens to withdraw
*/
function withdrawTokens(uint256 _value) public override {
uint256 balance = token.balanceOf(address(this));
require(_value <= balance, "Not enough tokens in the contract");
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableReward = getAvailableReward(msg.sender);
require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion");
delegator.withdrawnReward = delegator.withdrawnReward.add(_value);
totalWithdrawnReward = totalWithdrawnReward.add(_value);
token.safeTransfer(msg.sender, _value);
emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens);
}
/**
* @notice Withdraw reward, deposit and fee to delegator
*/
function withdrawAll() public {
uint256 balance = token.balanceOf(address(this));
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableReward = getAvailableReward(msg.sender);
uint256 value = availableReward.add(delegator.depositedTokens);
require(value <= balance, "Not enough tokens in the contract");
// TODO remove double reading
uint256 availableWorkerReward = getAvailableWorkerReward();
// potentially could be less then due reward
uint256 availableETH = getAvailableETH(msg.sender);
// prevent losing reward for worker after calculations
uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
if (workerReward > 0) {
require(value.add(workerReward) <= balance, "Not enough tokens in the contract");
token.safeTransfer(workerOwner, workerReward);
emit TokensWithdrawn(workerOwner, workerReward, 0);
}
uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens);
workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease);
totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward);
totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens);
delegator.withdrawnReward = 0;
delegator.depositedTokens = 0;
token.safeTransfer(msg.sender, value);
emit TokensWithdrawn(msg.sender, value, 0);
totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH);
delegator.withdrawnETH = 0;
if (availableETH > 0) {
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
}
/**
* @notice Get available ether for delegator
*/
function getAvailableETH(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 balance = address(this).balance;
// ETH balance + already withdrawn - (refunded - refundWithdrawn)
balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded);
uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens);
uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/**
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawETH() public override {
Delegator storage delegator = delegators[msg.sender];
calculateAndSaveTokensAmount(delegator);
uint256 availableETH = getAvailableETH(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH);
totalWithdrawnETH = totalWithdrawnETH.add(availableETH);
msg.sender.sendValue(availableETH);
emit ETHWithdrawn(msg.sender, availableETH);
}
/**
* @notice Withdraw compensation and refund from WorkLock and save these numbers
*/
function refund() public {
uint256 balance = address(this).balance;
if (workLock.compensation(address(this)) > 0) {
workLock.withdrawCompensation();
}
workLock.refund();
uint256 refundETH = address(this).balance - balance;
totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH);
emit Refund(address(this), refundETH);
}
/**
* @notice Get available refund for delegator
*/
function getAvailableRefund(address _delegator) public view returns (uint256) {
Delegator storage delegator = delegators[_delegator];
uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock)
.div(totalWorkLockETHReceived);
uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock);
uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn);
if (availableETH > balance) {
availableETH = balance;
}
return availableETH;
}
/*
* @notice Withdraw available amount of ETH to delegator
*/
function withdrawRefund() external {
uint256 availableETH = getAvailableRefund(msg.sender);
require(availableETH > 0, "There is no available ETH to withdraw");
Delegator storage delegator = delegators[msg.sender];
delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH);
totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH);
msg.sender.sendValue(availableETH);
emit Refund(msg.sender, availableETH);
}
/**
* @notice Calling fallback function is allowed only for the owner
*/
function isFallbackAllowed() public override view returns (bool) {
return msg.sender == owner();
}
}
| Interface for Voting contract, as found in https:github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol Public getters Setters Creating new votes Voting Executing a passed vote Additional info | interface Voting is IForwarder{
function token() external returns (address);
function supportRequiredPct() external returns (uint64);
function minAcceptQuorumPct() external returns (uint64);
function voteTime() external returns (uint64);
function votesLength() external returns (uint256);
function changeSupportRequiredPct(uint64 _supportRequiredPct) external;
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external;
function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId);
function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided)
external returns (uint256 voteId);
function canVote(uint256 _voteId, address _voter) external view returns (bool);
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external;
function canExecute(uint256 _voteId) external view returns (bool);
function executeVote(uint256 _voteId) external;
function getVote(uint256 _voteId) external view
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes memory script
);
function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState);
enum VoterState { Absent, Yea, Nay }
}
| 1,393,307 |
./full_match/1/0x7EAdDe89C43B9577526cdF0714cC987D08A87992/sources/lend-core/contracts/interfaces/IInitializableDebtToken.sol | IInitializableDebtToken HopeLend Interface for the initialize function common between debt tokens/ | interface IInitializableDebtToken {
event Initialized(
address indexed underlyingAsset,
address indexed pool,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
function initialize(
IPool pool,
address underlyingAsset,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
pragma solidity 0.8.17;
import {IPool} from './IPool.sol';
}
| 17,099,204 |
./full_match/1/0xF74480d927D3D34dE74C861841FCaFA2f7701617/sources/contracts/Base.sol | Returns to normal state. Requirements: - The contract must be paused./ | function unpause() public onlyAdmin {
super._unpause();
}
| 16,400,055 |
./full_match/1/0xBb24B5cdEa5DaEdac1158950dA9B01f84eddAE84/sources/FMTPrivateDistribution.sol | Adds Distribution. This function doesn't limit max gas consumption, so adding too many investors can cause it to reach the out-of-gas error. _beneficiary The address of distribution. _tokensAllotment The amounts of the tokens that belong to each investor. | function _addDistribution(
address _beneficiary,
DistributionType _distributionType,
uint256 _tokensAllotment
) internal {
require(_beneficiary != address(0), "Invalid address");
require(
_tokensAllotment > 0,
"the investor allocation must be more than 0"
);
Distribution storage distribution = distributionInfo[_distributionType];
require(distribution.tokensAllotment == 0, "investor already added");
distribution.beneficiary = _beneficiary;
distribution.tokensAllotment = _tokensAllotment;
distribution.distributionType = _distributionType;
emit DistributionAdded(_beneficiary, _msgSender(), _tokensAllotment);
}
| 3,216,379 |
/*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
import {SafeMath} from "../../lib/SafeMath.sol";
import {InitializableOwnable} from "../../lib/InitializableOwnable.sol";
import {IERC721} from "../../intf/IERC721.sol";
import {IERC721Receiver} from "../../intf/IERC721Receiver.sol";
import {IERC1155} from "../../intf/IERC1155.sol";
import {IERC1155Receiver} from "../../intf/IERC1155Receiver.sol";
import {ReentrancyGuard} from "../../lib/ReentrancyGuard.sol";
contract NFTCollateralVault is InitializableOwnable, IERC721Receiver, IERC1155Receiver, ReentrancyGuard {
using SafeMath for uint256;
// ============ Storage ============
string public name;
string public baseURI;
function init(
address owner,
string memory _name,
string memory _baseURI
) external {
initOwner(owner);
name = _name;
baseURI = _baseURI;
}
// ============ Event ============
event RemoveNftToken(address nftContract, uint256 tokenId, uint256 amount);
event AddNftToken(address nftContract, uint256 tokenId, uint256 amount);
// ============ TransferFrom NFT ============
function depositERC721(address nftContract, uint256[] memory tokenIds) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), tokenIds[i]);
// emit AddNftToken(nftContract, tokenIds[i], 1);
}
}
function depoistERC1155(address nftContract, uint256[] memory tokenIds, uint256[] memory amounts) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
require(tokenIds.length == amounts.length, "PARAMS_NOT_MATCH");
IERC1155(nftContract).safeBatchTransferFrom(msg.sender, address(this), tokenIds, amounts, "");
// for(uint256 i = 0; i < tokenIds.length; i++) {
// emit AddNftToken(nftContract, tokenIds[i], amounts[i]);
// }
}
// ============ Ownable ============
function directTransferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "DODONftVault: ZERO_ADDRESS");
emit OwnershipTransferred(_OWNER_, newOwner);
_OWNER_ = newOwner;
}
function createFragment(address nftProxy, bytes calldata data) external preventReentrant onlyOwner {
require(nftProxy != address(0), "DODONftVault: PROXY_INVALID");
_OWNER_ = nftProxy;
(bool success,) = nftProxy.call(data);
require(success, "DODONftVault: TRANSFER_OWNER_FAILED");
emit OwnershipTransferred(_OWNER_, nftProxy);
}
function withdrawERC721(address nftContract, uint256[] memory tokenIds) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(address(this), _OWNER_, tokenIds[i]);
emit RemoveNftToken(nftContract, tokenIds[i], 1);
}
}
function withdrawERC1155(address nftContract, uint256[] memory tokenIds, uint256[] memory amounts) external onlyOwner {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
require(tokenIds.length == amounts.length, "PARAMS_NOT_MATCH");
IERC1155(nftContract).safeBatchTransferFrom(address(this), _OWNER_, tokenIds, amounts, "");
for(uint256 i = 0; i < tokenIds.length; i++) {
emit RemoveNftToken(nftContract, tokenIds[i], amounts[i]);
}
}
function supportsInterface(bytes4 interfaceId) public override view returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId
|| interfaceId == type(IERC721Receiver).interfaceId;
}
// ============ Callback ============
function onERC721Received(
address,
address,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
emit AddNftToken(msg.sender, tokenId, 1);
return IERC721Receiver.onERC721Received.selector;
}
function onERC1155Received(
address,
address,
uint256 id,
uint256 value,
bytes calldata
) external override returns (bytes4){
emit AddNftToken(msg.sender, id, value);
return IERC1155Receiver.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata
) external override returns (bytes4){
require(ids.length == values.length, "PARAMS_NOT_MATCH");
for(uint256 i = 0; i < ids.length; i++) {
emit AddNftToken(msg.sender, ids[i], values[i]);
}
return IERC1155Receiver.onERC1155BatchReceived.selector;
}
}
| ============ TransferFrom NFT ============ emit AddNftToken(nftContract, tokenIds[i], 1); | function depositERC721(address nftContract, uint256[] memory tokenIds) public {
require(nftContract != address(0), "DODONftVault: ZERO_ADDRESS");
for(uint256 i = 0; i < tokenIds.length; i++) {
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), tokenIds[i]);
}
}
| 5,406,115 |
/**
*Submitted for verification at Etherscan.io on 2020-10-28
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
// Subject to the MIT license.
/**
* Rekeep3r.network
* A standard implementation of kp3rv1 protocol
* Mint function capped
* Kept most of the original functionality
*/
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "add: +");
return c;
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "sub: -");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (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 0;
}
uint c = a * b;
require(c / a == b, "mul: *");
return c;
}
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "div: /");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint a, uint b) internal pure returns (uint) {
return mod(a, b, "mod: %");
}
function mod(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @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 Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value:amount}("");
require(success, "Address: reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: < 0");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: !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: !succeed");
}
}
}
library Keep3rV1Library {
function getReserve(address pair, address reserve) external view returns (uint) {
(uint _r0, uint _r1,) = IUniswapV2Pair(pair).getReserves();
if (IUniswapV2Pair(pair).token0() == reserve) {
return _r0;
} else if (IUniswapV2Pair(pair).token1() == reserve) {
return _r1;
} else {
return 0;
}
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IGovernance {
function proposeJob(address job) external;
}
interface IKeep3rV1Helper {
function getQuoteLimit(uint gasUsed) external view returns (uint);
}
contract Keep3rV1 is ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
/// @notice Keep3r Helper to set max prices for the ecosystem
IKeep3rV1Helper public KPRH;
/// @notice EIP-20 token name for this token
string public constant name = "reKeep3r";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "REKP3R";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
// introducing max cap for owner
uint256 public maxCap;
/// @notice Total number of tokens in circulation
uint public totalSupply = 0; // Initial 0
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @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;
mapping (address => mapping (address => uint)) internal allowances;
mapping (address => uint) internal balances;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)");
bytes32 public immutable DOMAINSEPARATOR;
/// @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 The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint votes;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
_delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 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), "delegateBySig: sig");
require(nonce == nonces[signatory]++, "delegateBySig: nonce");
require(now <= expiry, "delegateBySig: expired");
_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) public view returns (uint) {
require(blockNumber < block.number, "getPriorVotes:");
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 = votes[delegator].add(bonds[delegator][address(this)]);
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)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal {
uint32 blockNumber = safe32(block.number, "_writeCheckpoint: 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);
}
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint amount);
/// @notice Submit a job
event SubmitJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Apply credit to a job
event ApplyCredit(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Remove credit for a job
event RemoveJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Unbond credit for a job
event UnbondJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Added a Job
event JobAdded(address indexed job, uint block, address governance);
/// @notice Removed a job
event JobRemoved(address indexed job, uint block, address governance);
/// @notice Worked a job
event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block, uint amount);
/// @notice Keeper bonding
event KeeperBonding(address indexed keeper, uint block, uint active, uint bond);
/// @notice Keeper bonded
event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond);
/// @notice Keeper unbonding
event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond);
/// @notice Keeper unbound
event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond);
/// @notice Keeper slashed
event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash);
/// @notice Keeper disputed
event KeeperDispute(address indexed keeper, uint block);
/// @notice Keeper resolved
event KeeperResolved(address indexed keeper, uint block);
event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount);
/// @notice 1 day to bond to become a keeper
uint constant public BOND = 3 days;
/// @notice 14 days to unbond to remove funds from being a keeper
uint constant public UNBOND = 14 days;
/// @notice 3 days till liquidity can be bound
uint constant public LIQUIDITYBOND = 3 days;
/// @notice direct liquidity fee 0.3%
uint constant public FEE = 30;
uint constant public BASE = 10000;
/// @notice address used for ETH transfers
address constant public ETH = address(0xE);
/// @notice tracks all current bondings (time)
mapping(address => mapping(address => uint)) public bondings;
/// @notice tracks all current unbondings (time)
mapping(address => mapping(address => uint)) public unbondings;
/// @notice allows for partial unbonding
mapping(address => mapping(address => uint)) public partialUnbonding;
/// @notice tracks all current pending bonds (amount)
mapping(address => mapping(address => uint)) public pendingbonds;
/// @notice tracks how much a keeper has bonded
mapping(address => mapping(address => uint)) public bonds;
/// @notice tracks underlying votes (that don't have bond)
mapping(address => uint) public votes;
/// @notice total bonded (totalSupply for bonds)
uint public totalBonded = 0;
/// @notice tracks when a keeper was first registered
mapping(address => uint) public firstSeen;
/// @notice tracks if a keeper has a pending dispute
mapping(address => bool) public disputes;
/// @notice tracks last job performed for a keeper
mapping(address => uint) public lastJob;
/// @notice tracks the total job executions for a keeper
mapping(address => uint) public workCompleted;
/// @notice list of all jobs registered for the keeper system
mapping(address => bool) public jobs;
/// @notice the current credit available for a job
mapping(address => mapping(address => uint)) public credits;
/// @notice the balances for the liquidity providers
mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided;
/// @notice liquidity unbonding days
mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding;
/// @notice liquidity unbonding amounts
mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding;
/// @notice job proposal delay
mapping(address => uint) public jobProposalDelay;
/// @notice liquidity apply date
mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied;
/// @notice liquidity amount to apply
mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount;
/// @notice list of all current keepers
mapping(address => bool) public keepers;
/// @notice blacklist of keepers not allowed to participate
mapping(address => bool) public blacklist;
/// @notice traversable array of keepers to make external management easier
address[] public keeperList;
/// @notice traversable array of jobs to make external management easier
address[] public jobList;
/// @notice governance address for the governance contract
address public governance;
address public pendingGovernance;
/// @notice the liquidity token supplied by users paying for jobs
mapping(address => bool) public liquidityAccepted;
address[] public liquidityPairs;
uint internal _gasUsed;
constructor(address _kph, uint256 _maxCap) public {
// Set governance for this token
// There will only be a limited supply of tokens ever
governance = msg.sender;
DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this)));
KPRH = IKeep3rV1Helper(_kph);
maxCap = _maxCap;
}
/**
* @notice Add ETH credit to a job to be paid out for work
* @param job the job being credited
*/
function addCreditETH(address job) external payable {
require(jobs[job], "addCreditETH: !job");
uint _fee = msg.value.mul(FEE).div(BASE);
credits[job][ETH] = credits[job][ETH].add(msg.value.sub(_fee));
payable(governance).transfer(_fee);
emit AddCredit(ETH, job, msg.sender, block.number, msg.value);
}
/**
* @notice Add credit to a job to be paid out for work
* @param credit the credit being assigned to the job
* @param job the job being credited
* @param amount the amount of credit being added to the job
*/
function addCredit(address credit, address job, uint amount) external nonReentrant {
require(jobs[job], "addCreditETH: !job");
uint _before = IERC20(credit).balanceOf(address(this));
IERC20(credit).safeTransferFrom(msg.sender, address(this), amount);
uint _received = IERC20(credit).balanceOf(address(this)).sub(_before);
uint _fee = _received.mul(FEE).div(BASE);
credits[job][credit] = credits[job][credit].add(_received.sub(_fee));
IERC20(credit).safeTransfer(governance, _fee);
emit AddCredit(credit, job, msg.sender, block.number, _received);
}
/**
* @notice Add non transferable votes for governance
* @param voter to add the votes to
* @param amount of votes to add
*/
function addVotes(address voter, uint amount) external {
require(msg.sender == governance, "addVotes: !gov");
_activate(voter, address(this));
votes[voter] = votes[voter].add(amount);
totalBonded = totalBonded.add(amount);
_moveDelegates(address(0), delegates[voter], amount);
}
/**
* @notice Remove non transferable votes for governance
* @param voter to subtract the votes
* @param amount of votes to remove
*/
function removeVotes(address voter, uint amount) external {
require(msg.sender == governance, "addVotes: !gov");
votes[voter] = votes[voter].sub(amount);
totalBonded = totalBonded.sub(amount);
_moveDelegates(delegates[voter], address(0), amount);
}
/**
* @notice Add credit to a job to be paid out for work
* @param job the job being credited
* @param amount the amount of credit being added to the job
*/
function addKPRCredit(address job, uint amount) external {
require(msg.sender == governance, "addKPRCredit: !gov");
require(jobs[job], "addKPRCredit: !job");
credits[job][address(this)] = credits[job][address(this)].add(amount);
_mint(address(this), amount);
emit AddCredit(address(this), job, msg.sender, block.number, amount);
}
/**
* @notice Approve a liquidity pair for being accepted in future
* @param liquidity the liquidity no longer accepted
*/
function approveLiquidity(address liquidity) external {
require(msg.sender == governance, "approveLiquidity: !gov");
require(!liquidityAccepted[liquidity], "approveLiquidity: !pair");
liquidityAccepted[liquidity] = true;
liquidityPairs.push(liquidity);
}
/**
* @notice Revoke a liquidity pair from being accepted in future
* @param liquidity the liquidity no longer accepted
*/
function revokeLiquidity(address liquidity) external {
require(msg.sender == governance, "revokeLiquidity: !gov");
liquidityAccepted[liquidity] = false;
}
/**
* @notice Displays all accepted liquidity pairs
*/
function pairs() external view returns (address[] memory) {
return liquidityPairs;
}
/**
* @notice Allows liquidity providers to submit jobs
* @param liquidity the liquidity being added
* @param job the job to assign credit to
* @param amount the amount of liquidity tokens to use
*/
function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant {
require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair");
IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount);
liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount);
liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND);
liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount);
if (!jobs[job] && jobProposalDelay[job] < now) {
IGovernance(governance).proposeJob(job);
jobProposalDelay[job] = now.add(UNBOND);
}
emit SubmitJob(job, liquidity, msg.sender, block.number, amount);
}
/**
* @notice Applies the credit provided in addLiquidityToJob to the job
* @param provider the liquidity provider
* @param liquidity the pair being added as liquidity
* @param job the job that is receiving the credit
*/
function applyCreditToJob(address provider, address liquidity, address job) external {
require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair");
require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond");
require(liquidityApplied[provider][liquidity][job] < now, "credit: bonding");
uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this));
uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply());
_mint(address(this), _credit);
credits[job][address(this)] = credits[job][address(this)].add(_credit);
liquidityAmount[provider][liquidity][job] = 0;
emit ApplyCredit(job, liquidity, provider, block.number, _credit);
}
/**
* @notice Unbond liquidity for a job
* @param liquidity the pair being unbound
* @param job the job being unbound from
* @param amount the amount of liquidity being removed
*/
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external {
require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit");
liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND);
liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount);
require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds");
uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this));
uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply());
if (_credit > credits[job][address(this)]) {
_burn(address(this), credits[job][address(this)]);
credits[job][address(this)] = 0;
} else {
_burn(address(this), _credit);
credits[job][address(this)] = credits[job][address(this)].sub(_credit);
}
emit UnbondJob(job, liquidity, msg.sender, block.number, amount);
}
/**
* @notice Allows liquidity providers to remove liquidity
* @param liquidity the pair being unbound
* @param job the job being unbound from
*/
function removeLiquidityFromJob(address liquidity, address job) external {
require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond");
require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding");
uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job];
liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount);
liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0;
IERC20(liquidity).safeTransfer(msg.sender, _amount);
emit RemoveJob(job, liquidity, msg.sender, block.number, _amount);
}
/**
* @notice Allows governance to mint new tokens to treasury
* @param amount the amount of tokens to mint to treasury
* fork from the original implementation limiting the max supply of tokens
*/
function mint(uint amount) external {
require(msg.sender == governance, "mint: !gov");
require(totalSupply.add(amount) <= maxCap);
_mint(governance, amount);
}
/**
* @notice burn owned tokens
* @param amount the amount of tokens to burn
*/
function burn(uint amount) external {
_burn(msg.sender, amount);
}
function _mint(address dst, uint amount) internal {
// mint the amount
totalSupply = totalSupply.add(amount);
// transfer the amount to the recipient
balances[dst] = balances[dst].add(amount);
emit Transfer(address(0), dst, amount);
}
function _burn(address dst, uint amount) internal {
require(dst != address(0), "_burn: zero address");
balances[dst] = balances[dst].sub(amount, "_burn: exceeds balance");
totalSupply = totalSupply.sub(amount);
emit Transfer(dst, address(0), amount);
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param keeper address of the keeper that performed the work
*/
function worked(address keeper) external {
workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft())));
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param keeper address of the keeper that performed the work
* @param amount the reward that should be allocated
*/
function workReceipt(address keeper, uint amount) public {
require(jobs[msg.sender], "wRec: !job");
require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "wRec: max limit");
credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "wRec: insuffient funds");
lastJob[keeper] = now;
_reward(keeper, amount);
workCompleted[keeper] = workCompleted[keeper].add(amount);
emit KeeperWorked(address(this), msg.sender, keeper, block.number, amount);
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param credit the asset being awarded to the keeper
* @param keeper address of the keeper that performed the work
* @param amount the reward that should be allocated
*/
function receipt(address credit, address keeper, uint amount) external {
require(jobs[msg.sender], "receipt: !job");
credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "wRec: insuffient funds");
lastJob[keeper] = now;
IERC20(credit).safeTransfer(keeper, amount);
emit KeeperWorked(credit, msg.sender, keeper, block.number, amount);
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param keeper address of the keeper that performed the work
* @param amount the amount of ETH sent to the keeper
*/
function receiptETH(address keeper, uint amount) external {
require(jobs[msg.sender], "receipt: !job");
credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "wRec: insuffient funds");
lastJob[keeper] = now;
payable(keeper).transfer(amount);
emit KeeperWorked(ETH, msg.sender, keeper, block.number, amount);
}
function _reward(address _from, uint _amount) internal {
bonds[_from][address(this)] = bonds[_from][address(this)].add(_amount);
totalBonded = totalBonded.add(_amount);
_moveDelegates(address(0), delegates[_from], _amount);
emit Transfer(msg.sender, _from, _amount);
}
function _bond(address bonding, address _from, uint _amount) internal {
bonds[_from][bonding] = bonds[_from][bonding].add(_amount);
if (bonding == address(this)) {
totalBonded = totalBonded.add(_amount);
_moveDelegates(address(0), delegates[_from], _amount);
}
}
function _unbond(address bonding, address _from, uint _amount) internal {
bonds[_from][bonding] = bonds[_from][bonding].sub(_amount);
if (bonding == address(this)) {
totalBonded = totalBonded.sub(_amount);
_moveDelegates(delegates[_from], address(0), _amount);
}
}
/**
* @notice Allows governance to add new job systems
* @param job address of the contract for which work should be performed
*/
function addJob(address job) external {
require(msg.sender == governance, "addJob: !gov");
require(!jobs[job], "addJob: job known");
jobs[job] = true;
jobList.push(job);
emit JobAdded(job, block.number, msg.sender);
}
/**
* @notice Full listing of all jobs ever added
* @return array blob
*/
function getJobs() external view returns (address[] memory) {
return jobList;
}
/**
* @notice Allows governance to remove a job from the systems
* @param job address of the contract for which work should be performed
*/
function removeJob(address job) external {
require(msg.sender == governance, "removeJob: !gov");
jobs[job] = false;
emit JobRemoved(job, block.number, msg.sender);
}
/**
* @notice Allows governance to change the Keep3rHelper for max spend
* @param _kprh new helper address to set
*/
function setKeep3rHelper(IKeep3rV1Helper _kprh) external {
require(msg.sender == governance, "setKeep3rHelper: !gov");
KPRH = _kprh;
}
/**
* @notice Allows governance to change governance (for future upgradability)
* @param _governance new governance address to set
*/
function setGovernance(address _governance) external {
require(msg.sender == governance, "setGovernance: !gov");
pendingGovernance = _governance;
}
/**
* @notice Allows pendingGovernance to accept their role as governance (protection pattern)
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov");
governance = pendingGovernance;
}
/**
* @notice confirms if the current keeper is registered, can be used for general (non critical) functions
* @param keeper the keeper being investigated
* @return true/false if the address is a keeper
*/
function isKeeper(address keeper) external returns (bool) {
_gasUsed = gasleft();
return keepers[keeper];
}
/**
* @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions
* @param keeper the keeper being investigated
* @param minBond the minimum requirement for the asset provided in bond
* @param earned the total funds earned in the keepers lifetime
* @param age the age of the keeper in the system
* @return true/false if the address is a keeper and has more than the bond
*/
function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) {
_gasUsed = gasleft();
return keepers[keeper]
&& bonds[keeper][address(this)].add(votes[keeper]) >= minBond
&& workCompleted[keeper] >= earned
&& now.sub(firstSeen[keeper]) >= age;
}
/**
* @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions
* @param keeper the keeper being investigated
* @param bond the bound asset being evaluated
* @param minBond the minimum requirement for the asset provided in bond
* @param earned the total funds earned in the keepers lifetime
* @param age the age of the keeper in the system
* @return true/false if the address is a keeper and has more than the bond
*/
function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) {
_gasUsed = gasleft();
return keepers[keeper]
&& bonds[keeper][bond] >= minBond
&& workCompleted[keeper] >= earned
&& now.sub(firstSeen[keeper]) >= age;
}
/**
* @notice begin the bonding process for a new keeper
* @param bonding the asset being bound
* @param amount the amount of bonding asset being bound
*/
function bond(address bonding, uint amount) external nonReentrant {
require(!blacklist[msg.sender], "bond: blacklisted");
bondings[msg.sender][bonding] = now.add(BOND);
if (bonding == address(this)) {
_transferTokens(msg.sender, address(this), amount);
} else {
uint _before = IERC20(bonding).balanceOf(address(this));
IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount);
amount = IERC20(bonding).balanceOf(address(this)).sub(_before);
}
pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount);
emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount);
}
/**
* @notice get full list of keepers in the system
*/
function getKeepers() external view returns (address[] memory) {
return keeperList;
}
/**
* @notice allows a keeper to activate/register themselves after bonding
* @param bonding the asset being activated as bond collateral
*/
function activate(address bonding) external {
require(!blacklist[msg.sender], "activate: blacklisted");
require(bondings[msg.sender][bonding] != 0 && bondings[msg.sender][bonding] < now, "activate: bonding");
_activate(msg.sender, bonding);
}
function _activate(address keeper, address bonding) internal {
if (firstSeen[keeper] == 0) {
firstSeen[keeper] = now;
keeperList.push(keeper);
lastJob[keeper] = now;
}
keepers[keeper] = true;
_bond(bonding, keeper, pendingbonds[keeper][bonding]);
pendingbonds[keeper][bonding] = 0;
emit KeeperBonded(keeper, block.number, block.timestamp, bonds[keeper][bonding]);
}
/**
* @notice begin the unbonding process to stop being a keeper
* @param bonding the asset being unbound
* @param amount allows for partial unbonding
*/
function unbond(address bonding, uint amount) external {
unbondings[msg.sender][bonding] = now.add(UNBOND);
_unbond(bonding, msg.sender, amount);
partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount);
emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount);
}
/**
* @notice withdraw funds after unbonding has finished
* @param bonding the asset to withdraw from the bonding pool
*/
function withdraw(address bonding) external nonReentrant {
require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "withdraw: unbonding");
require(!disputes[msg.sender], "withdraw: disputes");
if (bonding == address(this)) {
_transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]);
} else {
IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]);
}
emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]);
partialUnbonding[msg.sender][bonding] = 0;
}
/**
* @notice allows governance to create a dispute for a given keeper
* @param keeper the address in dispute
*/
function dispute(address keeper) external {
require(msg.sender == governance, "dispute: !gov");
disputes[keeper] = true;
emit KeeperDispute(keeper, block.number);
}
/**
* @notice allows governance to slash a keeper based on a dispute
* @param bonded the asset being slashed
* @param keeper the address being slashed
* @param amount the amount being slashed
*/
function slash(address bonded, address keeper, uint amount) public nonReentrant {
require(msg.sender == governance, "slash: !gov");
if (bonded == address(this)) {
_transferTokens(address(this), governance, amount);
} else {
IERC20(bonded).safeTransfer(governance, amount);
}
_unbond(bonded, keeper, amount);
disputes[keeper] = false;
emit KeeperSlashed(keeper, msg.sender, block.number, amount);
}
/**
* @notice blacklists a keeper from participating in the network
* @param keeper the address being slashed
*/
function revoke(address keeper) external {
require(msg.sender == governance, "slash: !gov");
keepers[keeper] = false;
blacklist[keeper] = true;
slash(address(this), keeper, bonds[keeper][address(this)]);
}
/**
* @notice allows governance to resolve a dispute on a keeper
* @param keeper the address cleared
*/
function resolve(address keeper) external {
require(msg.sender == governance, "resolve: !gov");
disputes[keeper] = false;
emit KeeperResolved(keeper, block.number);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint amount) public returns (bool) {
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline 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 permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "permit: signature");
require(signatory == owner, "permit: unauthorized");
require(now <= deadline, "permit: expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint amount) public returns (bool) {
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint amount) external returns (bool) {
address spender = msg.sender;
uint spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint(-1)) {
uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function _transferTokens(address src, address dst, uint amount) internal {
require(src != address(0), "_transferTokens: zero address");
require(dst != address(0), "_transferTokens: zero address");
balances[src] = balances[src].sub(amount, "_transferTokens: exceeds balance");
balances[dst] = balances[dst].add(amount, "_transferTokens: overflows");
emit Transfer(src, dst, amount);
}
function _getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
} | Allows governance to remove a job from the systems job address of the contract for which work should be performed/ | function removeJob(address job) external {
require(msg.sender == governance, "removeJob: !gov");
jobs[job] = false;
emit JobRemoved(job, block.number, msg.sender);
}
| 256,313 |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | inject NONSTANDARD NAMING | function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { | 14,087,757 |
pragma solidity ^0.5.2;
/**
* @title ERC777 token interface
* @dev See https://eips.ethereum.org/EIPS/eip-777
*/
interface IERC777 {
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function send(address to, uint256 amount, bytes calldata data) external;
function operatorSend(
address from,
address to,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
function burn(uint256 amount, bytes calldata data) external;
function operatorBurn(
address from,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function granularity() external view returns (uint256);
function defaultOperators() external view returns (address[] memory);
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
| ERC777 token interface/ | interface IERC777 {
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function send(address to, uint256 amount, bytes calldata data) external;
function operatorSend(
address from,
address to,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
function burn(uint256 amount, bytes calldata data) external;
function operatorBurn(
address from,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function granularity() external view returns (uint256);
function defaultOperators() external view returns (address[] memory);
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
| 7,318,058 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "./IO.sol";
import "./Storage.sol";
import "./Constants.sol";
import "./IveCurveVault.sol";
import "./IOneInch.sol";
import "./ICurve.sol";
import "./IATokenV1.sol";
import "./ICToken.sol";
import "./IComptroller.sol";
import "./ISushiBar.sol";
import "./ILendingPoolV1.sol";
import "./ICompoundLens.sol";
import "./IYearn.sol";
import "./IERC20.sol";
import "./SafeERC20.sol";
import "./SafeMath.sol";
contract RebalancingV3 is Storage, Constants, IO {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Match
address constant ZERO_X = 0xDef1C0ded9bec7F1a1670819833240f027b25EfF;
// 1inch
address constant ONE_SPLIT = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E;
// Aave
address constant LENDING_POOL_V1 = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address constant LENDING_POOL_CORE_V1 = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
// Sushi
address constant XSUSHI = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272;
// Curve
address constant CURVE_LINK = 0xF178C0b5Bb7e7aBF4e12A4838C7b7c5bA2C623c0;
// CTokens
address constant CUNI = 0x35A18000230DA775CAc24873d00Ff85BccdeD550;
address constant CCOMP = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
// ATokens v1
address constant AYFIv1 = 0x12e51E77DAAA58aA0E9247db7510Ea4B46F9bEAd;
address constant ASNXv1 = 0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE;
address constant AMKRv1 = 0x7deB5e830be29F91E298ba5FF1356BB7f8146998;
address constant ARENv1 = 0x69948cC03f478B95283F7dbf1CE764d0fc7EC54C;
address constant AKNCv1 = 0x9D91BE44C06d373a8a226E1f3b146956083803eB;
// Yearn tokens
address constant yveCRV = 0xc5bDdf9843308380375a611c18B50Fb9341f502A;
address constant yvBOOST = 0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a;
// Curve Tokens
address constant linkCRV = 0xcee60cFa923170e4f8204AE08B4fA6A3F5656F3a;
address constant gaugeLinkCRV = 0xFD4D8a17df4C27c1dD245d153ccf4499e806C87D;
// Underlyings
address constant LINK = 0x514910771AF9Ca656af840dff83E8264EcF986CA;
address constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address constant UNI = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984;
address constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address constant YFI = 0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e;
address constant SNX = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F;
address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;
address constant REN = 0x408e41876cCCDC0F92210600ef50372656052a38;
address constant KNC = 0xdd974D5C2e2928deA5F71b9825b8b646686BD200;
address constant LRC = 0xBBbbCA6A901c926F240b89EacB641d8Aec7AEafD;
address constant BAL = 0xba100000625a3754423978a60c9317c58a424e3D;
address constant AAVE = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9;
address constant MTA = 0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2;
address constant SUSHI = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2;
// **** Rebalance ****
function rebalance(
address _from,
address _to,
uint256 _amount,
uint256 _minRecvAmount,
bytes calldata _data
) external returns (uint256) {
_requireAssetData(_from);
// Limit number of 'to' assets
// Rebalance might introduce a new asset, asset can only be yveCRV or linkCRV
bool hasTo = _hasAssetData(_to);
require(hasTo || _to == CRV || _to == LINK, "!to");
if (!hasTo) {
assets.push(_to);
}
address fromUnderlying = _from;
uint256 fromUnderlyingAmount = _amount;
address toUnderlying = _getUnderlying(_to);
// Unwrap to underlying
if (_isCToken(_from)) {
(fromUnderlying, fromUnderlyingAmount) = _fromCToken(_from, _amount);
} else if (_isATokenV1(_from)) {
(fromUnderlying, fromUnderlyingAmount) = _fromATokenV1(_from, _amount);
} else if (_from == XSUSHI) {
(fromUnderlying, fromUnderlyingAmount) = _fromXSushi(_amount);
} else if (_from == yveCRV) {
// Wrap to BOOST and then swap cuz there's more liquidity that way
(fromUnderlying, fromUnderlyingAmount) = _toYveBoost(_amount);
} else if (_from == linkCRV) {
// Unwrap from CURVE to LINK
(fromUnderlying, fromUnderlyingAmount) = _fromLinkCRV(_amount);
}
// Swap on matcha
IERC20(fromUnderlying).safeApprove(ZERO_X, 0);
IERC20(fromUnderlying).safeApprove(ZERO_X, fromUnderlyingAmount);
(bool success, ) = ZERO_X.call(_data);
require(success, "!swap");
// Re-wrap to derivative
uint256 toAmount = IERC20(toUnderlying).balanceOf(address(this));
require(toAmount >= _minRecvAmount, "!min-amount");
if (_isCToken(_to)) {
_toCToken(toUnderlying, toAmount);
} else if (_isATokenV1(_to)) {
_toATokenV1(toUnderlying, toAmount);
} else if (_to == yveCRV) {
// Should have CRV
_toYveCRV(toAmount);
} else if (_to == linkCRV) {
_toLinkCRV(toAmount);
}
}
function toYveCRV() external {
_requireAssetData(CRV);
uint256 _balance = IERC20(CRV).balanceOf(address(this));
_toYveCRV(_balance);
_overrideAssetData(CRV, yveCRV);
}
function toLinkCRV() external {
_requireAssetData(LINK);
uint256 _balance = IERC20(LINK).balanceOf(address(this));
_toLinkCRV(_balance);
_overrideAssetData(LINK, linkCRV);
}
function toGaugeLinkCRV() external {
_requireAssetData(linkCRV);
uint256 _balance = IERC20(linkCRV).balanceOf(address(this));
_toGaugeLinkCRV(_balance);
_overrideAssetData(linkCRV, gaugeLinkCRV);
}
// **** Internal ****
/// @notice Supplies assets to the Compound market
/// @param _token Underlying token to supply to Compound
function _toCToken(address _token, uint256 _amount) internal returns (address, uint256) {
address _ctoken = _getTokenToCToken(_token);
uint256 _before = IERC20(_ctoken).balanceOf(address(this));
IERC20(_token).safeApprove(_ctoken, 0);
IERC20(_token).safeApprove(_ctoken, _amount);
require(ICToken(_ctoken).mint(_amount) == 0, "!ctoken-mint");
uint256 _after = IERC20(_ctoken).balanceOf(address(this));
return (_ctoken, _after.sub(_before));
}
/// @notice Redeems assets from the Compound market
/// @param _ctoken CToken to redeem from Compound
function _fromCToken(address _ctoken, uint256 _amount) internal returns (address, uint256) {
address _token = ICToken(_ctoken).underlying();
uint256 _before = IERC20(_token).balanceOf(address(this));
require(ICToken(_ctoken).redeem(_amount) == 0, "!ctoken-redeem");
uint256 _after = IERC20(_token).balanceOf(address(this));
return (_token, _after.sub(_before));
}
/// @notice Supplies assets to the Aave market
/// @param _token Underlying to supply to Aave
function _toATokenV1(address _token, uint256 _amount) internal returns (address, uint256) {
(, , , , , , , , , , , address _atoken, ) = ILendingPoolV1(LENDING_POOL_V1).getReserveData(_token);
uint256 _before = IERC20(_atoken).balanceOf(address(this));
IERC20(_token).safeApprove(LENDING_POOL_CORE_V1, 0);
IERC20(_token).safeApprove(LENDING_POOL_CORE_V1, _amount);
ILendingPoolV1(LENDING_POOL_V1).deposit(_token, _amount, 0);
// Redirect Interest
address feeRecipient = _readSlotAddress(FEE_RECIPIENT);
require(feeRecipient != address(0), "!fee-recipient");
if (feeRecipient != IATokenV1(_atoken).getInterestRedirectionAddress(address(this))) {
IATokenV1(_atoken).redirectInterestStream(feeRecipient);
}
uint256 _after = IERC20(_atoken).balanceOf(address(this));
return (_atoken, _after.sub(_before));
}
/// @notice Redeems assets from the Aave market
/// @param _atoken AToken to redeem from Aave
function _fromATokenV1(address _atoken, uint256 _amount) internal returns (address, uint256) {
address _token = IATokenV1(_atoken).underlyingAssetAddress();
uint256 _before = IERC20(_token).balanceOf(address(this));
IATokenV1(_atoken).redeem(_amount);
uint256 _after = IERC20(_token).balanceOf(address(this));
return (_token, _after.sub(_before));
}
/// @notice Converts sushi to xsushi
function _toXSushi(uint256 _amount) internal returns (address, uint256) {
uint256 _before = ISushiBar(XSUSHI).balanceOf(address(this));
IERC20(SUSHI).safeApprove(XSUSHI, 0);
IERC20(SUSHI).safeApprove(XSUSHI, _amount);
ISushiBar(XSUSHI).enter(_amount);
uint256 _after = ISushiBar(XSUSHI).balanceOf(address(this));
return (XSUSHI, _after.sub(_before));
}
/// @notice Goes from xsushi to sushi
function _fromXSushi(uint256 _amount) internal returns (address, uint256) {
uint256 _before = IERC20(SUSHI).balanceOf(address(this));
ISushiBar(XSUSHI).leave(_amount);
uint256 _after = IERC20(SUSHI).balanceOf(address(this));
return (SUSHI, _after.sub(_before));
}
/// @notice Converts link to linkCRV
function _toLinkCRV(uint256 _amount) internal returns (address, uint256) {
// Deposit into gauge
uint256 _before = IERC20(linkCRV).balanceOf(address(this));
IERC20(LINK).safeApprove(CURVE_LINK, 0);
IERC20(LINK).safeApprove(CURVE_LINK, _amount);
ICurveLINK(CURVE_LINK).add_liquidity([_amount, uint256(0)], 0);
uint256 _after = IERC20(linkCRV).balanceOf(address(this));
return (linkCRV, _after.sub(_before));
}
/// @notice Converts linkCRV to GaugeLinkCRV
function _toGaugeLinkCRV(uint256 _amount) internal returns (address, uint256) {
// Deposit into gauge
uint256 _before = IERC20(gaugeLinkCRV).balanceOf(address(this));
IERC20(linkCRV).safeApprove(gaugeLinkCRV, 0);
IERC20(linkCRV).safeApprove(gaugeLinkCRV, _amount);
ILinkGauge(gaugeLinkCRV).deposit(_amount);
uint256 _after = IERC20(gaugeLinkCRV).balanceOf(address(this));
return (gaugeLinkCRV, _after.sub(_before));
}
/// @notice Converts GaugeLinkCRV to linkCRV
function _fromGaugeLinkCRV(uint256 _amount) internal returns (address, uint256) {
// Deposit into gauge
uint256 _before = IERC20(linkCRV).balanceOf(address(this));
ILinkGauge(gaugeLinkCRV).withdraw(_amount);
uint256 _after = IERC20(linkCRV).balanceOf(address(this));
return (linkCRV, _after.sub(_before));
}
/// @notice Converts linkCRV to link
function _fromLinkCRV(uint256 _amount) internal returns (address, uint256) {
uint256 _before = IERC20(LINK).balanceOf(address(this));
ICurveLINK(CURVE_LINK).remove_liquidity_one_coin(_amount, 0, 0);
uint256 _after = IERC20(LINK).balanceOf(address(this));
return (linkCRV, _after.sub(_before));
}
/// @notice Converts from crv to yveCRV
function _toYveCRV(uint256 _amount) internal returns (address, uint256) {
uint256 _before = IERC20(yveCRV).balanceOf(address(this));
IERC20(CRV).safeApprove(yveCRV, 0);
IERC20(CRV).safeApprove(yveCRV, _amount);
IveCurveVault(yveCRV).deposit(_amount);
uint256 _after = IERC20(yveCRV).balanceOf(address(this));
return (yveCRV, _after.sub(_before));
}
/// @notice Converts from yveCRV to yvBOOST
function _toYveBoost(uint256 _amount) internal returns (address, uint256) {
uint256 _before = IERC20(yvBOOST).balanceOf(address(this));
IERC20(yveCRV).safeApprove(yvBOOST, 0);
IERC20(yveCRV).safeApprove(yvBOOST, _amount);
IYearn(yvBOOST).deposit(_amount);
uint256 _after = IERC20(yvBOOST).balanceOf(address(this));
return (yvBOOST, _after.sub(_before));
}
/// @notice Converts from yveCRV to yvBOOST
function _fromYveBoost(uint256 _amount) internal returns (address, uint256) {
uint256 _before = IERC20(yveCRV).balanceOf(address(this));
IYearn(yvBOOST).withdraw(_amount);
uint256 _after = IERC20(yveCRV).balanceOf(address(this));
return (yveCRV, _after.sub(_before));
}
/// @dev Token to CToken mapping
/// @param _token Token address
function _getTokenToCToken(address _token) internal pure returns (address) {
if (_token == UNI) {
return CUNI;
}
if (_token == COMP) {
return CCOMP;
}
revert("!supported-token-to-ctoken");
}
/// @dev Get wrapped token underlying
/// @param _derivative Derivative token address
function _getUnderlying(address _derivative) internal pure returns (address) {
if (_derivative == CUNI) {
return UNI;
}
if (_derivative == CCOMP) {
return COMP;
}
if (_derivative == XSUSHI) {
return SUSHI;
}
if (_derivative == AYFIv1) {
return YFI;
}
if (_derivative == ASNXv1) {
return SNX;
}
if (_derivative == AMKRv1) {
return MKR;
}
if (_derivative == ARENv1) {
return REN;
}
if (_derivative == AKNCv1) {
return KNC;
}
if (_derivative == yveCRV || _derivative == yvBOOST) {
return CRV;
}
if (_derivative == linkCRV) {
return LINK;
}
return _derivative;
}
function _isCTokenUnderlying(address _token) internal pure returns (bool) {
return (_token == UNI || _token == COMP);
}
function _isCToken(address _token) internal pure returns (bool) {
return (_token == CUNI || _token == CCOMP);
}
function _isATokenV1(address _token) internal pure returns (bool) {
return (_token == AYFIv1 || _token == ASNXv1 || _token == AMKRv1 || _token == ARENv1 || _token == AKNCv1);
}
function _isATokenV1Underlying(address _token) internal pure returns (bool) {
return (_token == YFI || _token == SNX || _token == MKR || _token == REN || _token == KNC);
}
/// @dev Requires `_from` to be present in the `assets` variable in `Storage.sol`
/// @param _from Token address
function _hasAssetData(address _from) internal view returns (bool) {
for (uint256 i = 0; i < assets.length; i++) {
if (assets[i] == _from) {
return true;
}
}
return false;
}
/// @dev Requires `_from` to be present in the `assets` variable in `Storage.sol`
/// @param _from Token address
function _requireAssetData(address _from) internal view {
require(_hasAssetData(_from), "!asset");
}
/// @dev Changes `_from` to `_to` in the `assets` variable in `Storage.sol`
/// @param _from Token address to change from
/// @param _to Token address to change to
function _overrideAssetData(address _from, address _to) internal {
// Override asset data
for (uint256 i = 0; i < assets.length; i++) {
if (assets[i] == _from) {
assets[i] = _to;
return;
}
}
}
} | Converts linkCRV to link | function _fromLinkCRV(uint256 _amount) internal returns (address, uint256) {
uint256 _before = IERC20(LINK).balanceOf(address(this));
ICurveLINK(CURVE_LINK).remove_liquidity_one_coin(_amount, 0, 0);
uint256 _after = IERC20(LINK).balanceOf(address(this));
return (linkCRV, _after.sub(_before));
}
| 284,103 |
./full_match/80001/0x921331433c9167F0EcD95F5E6841C032843Ce130/sources/project_/contracts/STokenV1.sol | Burns amounts of tokens from the array `_bundleAmounts` from the addresses of the array of addresses `_bundleFrom` Allowed only for MasterManager Address => value burnt according to indexes of arrays: from [0]indexed address will be burnt [0]indexed amount of tokens, from [1]indexed address will be burnt [1]indexed amount of tokens and so on _bundleFrom array of addresses to burn tokens from _bundleAmounts array of amounts of tokens to burn | function burn(address[] memory _bundleFrom, uint256[] memory _bundleAmounts)
external
onlyMasterManager
{
_bundlesLoop(_bundleFrom, _bundleAmounts, _burn);
}
| 5,596,179 |
/*
Copyright 2017 Dharma 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.
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
// Internal dependencies.
import "./DebtRegistry.sol";
import "../contracts/ERC165/IERC165.sol";
import { PermissionsLib, PermissionEvents } from "../contracts/libraries/PermissionsLib.sol";
// External dependencies.
import "../contracts/lifecycle/Pausable.sol";
import "../contracts/ERC721/ERC721.sol";
import "./ERC20.sol";
/**
* The DebtToken contract governs all business logic for making a debt agreement
* transferable as an ERC721 non-fungible token. Additionally, the contract
* allows authorized contracts to trigger the minting of a debt agreement token
* and, in turn, the insertion of a debt issuance into the DebtRegsitry.
*
* Author: Nadav Hollander -- Github: nadavhollander
*/
contract DebtToken is ERC721, Pausable, PermissionEvents {
using PermissionsLib for PermissionsLib.Permissions;
DebtRegistry public registry;
PermissionsLib.Permissions internal tokenCreationPermissions;
PermissionsLib.Permissions internal tokenURIPermissions;
string public constant CREATION_CONTEXT = "debt-token-creation";
string public constant URI_CONTEXT = "debt-token-uri";
/**
* Constructor that sets the address of the debt registry.
*/
constructor(address _registry)
public
ERC721("DebtToken", "DDT")
{
registry = DebtRegistry(_registry);
}
/**
* ERC165 interface.
* Returns true for ERC721, false otherwise
*/
function supportsInterface(bytes4 interfaceID)
external
view
returns (bool _isSupported)
{
return interfaceID == 0x80ac58cd; // ERC721
}
/**
* Mints a unique debt token and inserts the associated issuance into
* the debt registry, if the calling address is authorized to do so.
*/
function create(
address _version,
address _beneficiary,
address _debtor,
address _underwriter,
uint _underwriterRiskRating,
address _termsContract,
bytes32 _termsContractParameters,
uint _salt
)
public
whenNotPaused
returns (uint _tokenId)
{
require(tokenCreationPermissions.isAuthorized(msg.sender));
bytes32 entryHash = registry.insert(
_version,
_beneficiary,
_debtor,
_underwriter,
_underwriterRiskRating,
_termsContract,
_termsContractParameters,
_salt
);
super._mint(_beneficiary, uint(entryHash));
return uint(entryHash);
}
/**
* Adds an address to the list of agents authorized to mint debt tokens.
*/
function addAuthorizedMintAgent(address _agent)
public
onlyOwner
{
tokenCreationPermissions.authorize(_agent, CREATION_CONTEXT);
}
/**
* Removes an address from the list of agents authorized to mint debt tokens
*/
function revokeMintAgentAuthorization(address _agent)
public
onlyOwner
{
tokenCreationPermissions.revokeAuthorization(_agent, CREATION_CONTEXT);
}
/**
* Returns the list of agents authorized to mint debt tokens
*/
function getAuthorizedMintAgents()
public
view
returns (address[] memory _agents)
{
return tokenCreationPermissions.getAuthorizedAgents();
}
/**
* Adds an address to the list of agents authorized to set token URIs.
*/
function addAuthorizedTokenURIAgent(address _agent)
public
onlyOwner
{
tokenURIPermissions.authorize(_agent, URI_CONTEXT);
}
/**
* Returns the list of agents authorized to set token URIs.
*/
function getAuthorizedTokenURIAgents()
public
view
returns (address[] memory _agents)
{
return tokenURIPermissions.getAuthorizedAgents();
}
/**
* Removes an address from the list of agents authorized to set token URIs.
*/
function revokeTokenURIAuthorization(address _agent)
public
onlyOwner
{
tokenURIPermissions.revokeAuthorization(_agent, URI_CONTEXT);
}
/**
* We override approval method of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function approve(address _to, uint _tokenId)
public
whenNotPaused
{
super.approve(_to, _tokenId);
}
/**
* We override setApprovalForAll method of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function setApprovalForAll(address _to, bool _approved)
public
whenNotPaused
{
super.setApprovalForAll(_to, _approved);
}
/**
* Support deprecated ERC721 method
*/
function transfer(address _to, uint _tokenId)
public
{
safeTransferFrom(msg.sender, _to, _tokenId);
}
/**
* We override transferFrom methods of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function transferFrom(address _from, address _to, uint _tokenId)
public
whenNotPaused
{
_modifyBeneficiary(_tokenId, _to);
super.transferFrom(_from, _to, _tokenId);
}
/**
* We override safeTransferFrom methods of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function safeTransferFrom(address _from, address _to, uint _tokenId)
public
whenNotPaused
{
_modifyBeneficiary(_tokenId, _to);
super.safeTransferFrom(_from, _to, _tokenId);
}
/**
* We override safeTransferFrom methods of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function safeTransferFrom(address _from, address _to, uint _tokenId, bytes memory _data)
public
whenNotPaused
{
_modifyBeneficiary(_tokenId, _to);
super.safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* Allows senders with special permissions to set the token URI for a given debt token.
*/
function setTokenURI(uint256 _tokenId, string memory _uri)
public
whenNotPaused
{
require(tokenURIPermissions.isAuthorized(msg.sender));
super._setTokenURI(_tokenId, _uri);
}
/**
* _modifyBeneficiary mutates the debt registry. This function should be
* called every time a token is transferred or minted
*/
function _modifyBeneficiary(uint _tokenId, address _to)
internal
{
if (registry.getBeneficiary(bytes32(_tokenId)) != _to) {
registry.modifyBeneficiary(bytes32(_tokenId), _to);
}
}
}
| We override safeTransferFrom methods of the parent ERC721Token contract to allow its functionality to be frozen in the case of an emergency/ | function safeTransferFrom(address _from, address _to, uint _tokenId, bytes memory _data)
public
whenNotPaused
{
_modifyBeneficiary(_tokenId, _to);
super.safeTransferFrom(_from, _to, _tokenId, _data);
}
| 12,540,784 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
/**
* @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;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/* @dev 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 () {
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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev 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 ADORs is IERC20, Ownable {
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.
*/
constructor () {
_name = "ADORs";
_symbol = "ADORs";
_decimals = 18;
uint256 _maxSupply = 99999;
address manager = 0x244B84eD1150D994774bE96f71cDeca7BB16d4BC;
_mintTotalSupply(manager, _maxSupply.mul(10 ** _decimals));
}
receive() external payable {
revert();
}
/**
* @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 _mintTotalSupply(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
/**
* @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);
}
} | 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 _mintTotalSupply(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);
}
| 7,793,000 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract SimpleAuction {
// Parámetros de la subasta. Los tiempos son ellos
// marcas de tiempo absolutas de Unix (segundos desde 1970-01-01)
// o periodos de tiempo en segundos.
address payable public beneficiary;
uint public auctionEndTime;
// Estado actual de la subasta.
address public highestBidder;
uint public highestBid;
// Retiros permitidos de ofertas anteriores
mapping(address => uint) pendingReturns;
// Establecido en verdadero al final, no permite ningún cambio.
// Por defecto inicializado a `falso`.
bool ended;
// Eventos que se emitirán en los cambios.
event HighestBidIncreased(address bidder, uint amount);
event AuctionEnded(address winner, uint amount);
// Errores que describen fallas.
// Los comentarios de triple barra se denominan natspec
// comentarios. Se mostrarán cuando el usuario
// se le pide que confirme una transacción o
// cuando se muestra un error.
/// The auction has already ended.
error AuctionAlreadyEnded();
/// There is already a higher or equal bid.
error BidNotHighEnough(uint highestBid);
/// The auction has not ended yet.
error AuctionNotYetEnded();
/// The function auctionEnd has already been called.
error AuctionEndAlreadyCalled();
/// Cree una subasta simple con `_biddingTime`
/// segundos de tiempo de oferta en nombre del
/// dirección del beneficiario `_beneficiary`.
constructor(
uint _biddingTime,
address payable _beneficiary
) {
beneficiary = _beneficiary;
auctionEndTime = block.timestamp + _biddingTime;
}
/// Pujar en la subasta con el valor enviado
/// junto con esta transacción.
/// El valor solo se reembolsará si el
/// no se gana la subasta.
function bid() public payable {
// No son necesarios argumentos, todos
// la información ya es parte de
// la transacción. La palabra clave pagadero
// es necesario para que la función
// poder recibir Ether.
// Revertir la llamada si la puja
// el período ha terminado.
if (block.timestamp > auctionEndTime)
revert AuctionAlreadyEnded();
// Si la oferta no es mayor, envíe el
// devolución de dinero (la declaración de reversión
// revertirá todos los cambios en este
// ejecución de la función incluyendo
// habiendo recibido el dinero).
if (msg.value <= highestBid)
revert BidNotHighEnough(highestBid);
if (highestBid != 0) {
// Devolviendo el dinero simplemente usando
// maximumBidder.send (maximumBid) es un riesgo de seguridad
// porque podría ejecutar un contrato que no es de confianza.
// Siempre es más seguro dejar que los destinatarios
// retirar su dinero ellos mismos.
pendingReturns[highestBidder] += highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
emit HighestBidIncreased(msg.sender, msg.value);
}
/// Retirar una oferta que fue sobrepujada.
function withdraw() public returns (bool) {
uint amount = pendingReturns[msg.sender] = 0;
if (amount > 0) {
// Es importante establecer esto en cero porque el destinatario
// puede volver a llamar a esta función como parte de la llamada de recepción
// antes de que regrese `send`.
pendingReturns[msg.sender] = 0;
if (!payable(msg.sender).send(amount)) {
// No es necesario llamar a throw aquí, solo restablece la cantidad adeuda
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
/// Finalizar la subasta y enviar la oferta más alta
/// al beneficiario.
function auctionEnd() public {
// Es una buena guía para estructurar funciones que interactúan
// con otros contratos (es decir, llaman a funciones o envían Ether)
// en tres fases:
// 1. comprobar condiciones
// 2. realizar acciones (condiciones potencialmente cambiantes)
// 3. interactuar con otros contratos
// Si estas fases se mezclan, el otro contrato podría llamar
// volver al contrato actual y modificar el estado o la causa
// efectos (pago de ether) que se realizarán varias veces.
// Si las funciones llamadas internamente incluyen interacción con externas
// contratos, también deben considerarse interacción con
// contratos externos.
// 1. Condiciones
if (block.timestamp < auctionEndTime)
revert AuctionNotYetEnded();
if (ended)
revert AuctionEndAlreadyCalled();
// 2. Efectos
ended = true;
emit AuctionEnded(highestBidder, highestBid);
// 3. Interaction
beneficiary.transfer(highestBid);
}
} | Retirar una oferta que fue sobrepujada. Es importante establecer esto en cero porque el destinatario puede volver a llamar a esta función como parte de la llamada de recepción antes de que regrese `send`. No es necesario llamar a throw aquí, solo restablece la cantidad adeuda | function withdraw() public returns (bool) {
uint amount = pendingReturns[msg.sender] = 0;
if (amount > 0) {
pendingReturns[msg.sender] = 0;
if (!payable(msg.sender).send(amount)) {
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
| 15,854,173 |
./full_match/7700/0x626dA2533BFa6083349f199eA7c7B86EBbb63c34/sources/src/StrategyNeo.sol | swap rewards to {want} | function swapRewards() internal {
uint256 toWant = IERC20(output).balanceOf(address(this));
uint256 _before = IERC20(want).balanceOf(address(this));
if (token1 == output) {
uint256 toSwap = toWant / 2;
uint[] memory amounts = IUniswapRouter(unirouter)
.swapExactTokensForTokensSimple(
toSwap,
0,
output,
token2,
false,
address(this),
block.timestamp
);
IUniswapRouter(unirouter).addLiquidity(
token1,
token2,
false,
IERC20(token1).balanceOf(address(this)),
IERC20(token2).balanceOf(address(this)),
0,
0,
address(this),
block.timestamp
);
uint[] memory amounts1 = IUniswapRouter(unirouter)
.swapExactTokensForTokensSimple(
toWant,
0,
output,
note,
false,
address(this),
block.timestamp
);
uint256 toToken2 = IERC20(note).balanceOf(address(this)) / 2;
uint[] memory amounts2 = IUniswapRouter(unirouter)
.swapExactTokensForTokensSimple(
toToken2,
0,
note,
token2,
true,
address(this),
block.timestamp
);
IUniswapRouter(unirouter).addLiquidity(
token1,
token2,
true,
IERC20(token1).balanceOf(address(this)),
IERC20(token2).balanceOf(address(this)),
0,
0,
address(this),
block.timestamp
);
}
uint256 _after = IERC20(want).balanceOf(address(this));
if (_after > _before) {
uint256 totalHarvest = _after - _before;
uint256 toRewardCaller = (totalHarvest * callFee) / MAX_FEE;
IERC20(want).safeTransfer(tx.origin, toRewardCaller);
emit CallerRewards(toRewardCaller, tx.origin);
}
}
| 4,647,637 |
./full_match/10200/0x6e2CB44C51D6Ca432AE3252843fe0c234c466c6b/sources/newHashi/contracts/ownable/ShuSo.sol | Disables the given adapters for a given domain. domain Uint256 identifier for the domain for which to set oracle adapters. _adapters Array of oracleAdapter addresses. Reverts if _adapters are out of order or contain duplicates. Only callable by the owner of this contract. | function _disableOracleAdapters(uint256 domain, IOracleAdapter[] memory _adapters) internal onlyOwner {
if (domains[domain].count == 0) revert NoAdaptersEnabled(address(this), domain);
if (_adapters.length == 0) revert NoAdaptersGiven(address(this));
for (uint256 i = 0; i < _adapters.length; i++) {
IOracleAdapter adapter = _adapters[i];
if (adapter == IOracleAdapter(address(0)) || adapter == LIST_END)
revert InvalidAdapter(address(this), adapter);
Link memory current = adapters[domain][adapter];
if (current.next == IOracleAdapter(address(0))) revert AdapterNotEnabled(address(this), adapter);
IOracleAdapter next = current.next;
IOracleAdapter previous = current.previous;
adapters[domain][next].previous = previous;
adapters[domain][previous].next = next;
delete adapters[domain][adapter].next;
delete adapters[domain][adapter].previous;
domains[domain].count--;
}
emit OracleAdaptersDisabled(address(this), domain, _adapters);
}
| 3,784,679 |
// 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');
}
}
| set new Core reference address _newCore the new core address | function setCore(address _newCore) external override onlyGovernor {
_core = ICore(_newCore);
emit CoreUpdate(_newCore);
}
| 1,154,640 |
./full_match/5/0xaf7629ab114eFcC188Ee5ed6F186077740648Fe4/sources/contracts/ERC20.sol | Internal function that burns an amount of the token of a given account, deducting from the sender's allowance for said account. Uses the internal burn function. Emits an Approval event (reflecting the reduced allowance). account The account whose tokens will be burnt. value The amount that will be burnt./ | function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender] - value);
}
| 1,892,067 |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// ASTATO contract
//
// Symbol : ASTATO
// Name : ASTATO Token
// Description : Astato Network - Anonymous quota distribution
// Total supply: 6000000
// Decimals : 18
//
// (c) ASTATO Devs - MIT Licence.
// ----------------------------------------------------------------------------
// Infrastructure for distributed cryptographic systems
// ----------------------------------------------------------------------------
// 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);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract astatoToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
string public description;
uint8 public decimals;
uint public _totalSupply;
bool mainNet = true;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASTATO";
name = "ASTATO Token";
description = "Astato Network - Anonymous quota distribution";
decimals = 18;
_totalSupply = 6000000*(10**18);
if (mainNet) {
balances[0x5D11B9e7b0ec9C9e70b63b266346Bc9136eEd523] = _totalSupply;
emit Transfer(address(0), 0x5D11B9e7b0ec9C9e70b63b266346Bc9136eEd523, _totalSupply);
} else {
balances[0xf8b179CFe1bfDe3448D26C819dC756636C12fE5f] = _totalSupply; // ropsten
emit Transfer(address(0), 0xf8b179CFe1bfDe3448D26C819dC756636C12fE5f, _totalSupply); //ropsten
}
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ------------------------------------------------------------------------ Get the token balance for account tokenOwner ------------------------------------------------------------------------ | function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
| 13,789,181 |
./partial_match/56/0x41b98Df01000BD7EBb6d91c333C73c68e6CeBFC9/sources/src/strategies/BaseStrategy.sol | Sets the max token allowance for the specified spender. | function approveTokenMax(address token, address spender) internal {
IERC20Upgradeable(token).safeApprove(spender, type(uint256).max);
}
| 11,039,970 |
./full_match/44787/0x3D62177EdfC5894334877B70e588118D40D5eAC1/sources/project_/contracts/StandardToken.sol | 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(_enabledMint != false, "ERC20: feature disabled");
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);
}
| 13,256,189 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@powerpool/power-oracle/contracts/interfaces/IPowerPoke.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/WrappedPiErc20Interface.sol";
import "./interfaces/IPoolRestrictions.sol";
import "./interfaces/PowerIndexRouterInterface.sol";
import "./interfaces/IRouterConnector.sol";
import "./PowerIndexNaiveRouter.sol";
/**
* @notice PowerIndexRouter executes connectors with delegatecall to stake and redeem ERC20 tokens in
* protocol-specified staking contracts. After calling, it saves stakeData and pokeData as connectors storage.
* Available ERC20 token balance from piERC20 is distributed between connectors by its shares and calculated
* as the difference between total balance and share of necessary balance(reserveRatio) for keeping in piERC20
* for withdrawals.
*/
contract PowerIndexRouter is PowerIndexRouterInterface, PowerIndexNaiveRouter {
using SafeERC20 for IERC20;
uint256 internal constant COMPENSATION_PLAN_1_ID = 1;
uint256 public constant HUNDRED_PCT = 1 ether;
event SetReserveConfig(uint256 ratio, uint256 ratioLowerBound, uint256 ratioUpperBound, uint256 claimRewardsInterval);
event SetPerformanceFee(uint256 performanceFee);
event SetConnector(
IRouterConnector indexed connector,
uint256 share,
bool callBeforeAfterPoke,
uint256 indexed connectorIndex,
bool indexed isNewConnector
);
event SetConnectorClaimParams(address connector, bytes claimParams);
event SetConnectorStakeParams(address connector, bytes stakeParams);
struct BasicConfig {
address poolRestrictions;
address powerPoke;
uint256 reserveRatio;
uint256 reserveRatioLowerBound;
uint256 reserveRatioUpperBound;
uint256 claimRewardsInterval;
address performanceFeeReceiver;
uint256 performanceFee;
}
WrappedPiErc20Interface public immutable piToken;
IERC20 public immutable underlying;
address public immutable performanceFeeReceiver;
IPoolRestrictions public poolRestrictions;
IPowerPoke public powerPoke;
uint256 public reserveRatio;
uint256 public claimRewardsInterval;
uint256 public lastRebalancedAt;
uint256 public reserveRatioLowerBound;
uint256 public reserveRatioUpperBound;
// 1 ether == 100%
uint256 public performanceFee;
Connector[] public connectors;
struct RebalanceConfig {
bool shouldPushFunds;
StakeStatus status;
uint256 diff;
bool shouldClaim;
bool forceRebalance;
uint256 connectorIndex;
}
struct Connector {
IRouterConnector connector;
uint256 share;
bool callBeforeAfterPoke;
uint256 lastClaimRewardsAt;
uint256 lastChangeStakeAt;
bytes stakeData;
bytes pokeData;
bytes stakeParams;
bytes claimParams;
}
struct ConnectorInput {
bool newConnector;
uint256 connectorIndex;
IRouterConnector connector;
uint256 share;
bool callBeforeAfterPoke;
}
struct PokeFromState {
uint256 minInterval;
uint256 maxInterval;
uint256 piTokenUnderlyingBalance;
bool atLeastOneForceRebalance;
}
modifier onlyEOA() {
require(tx.origin == msg.sender, "ONLY_EOA");
_;
}
modifier onlyReporter(uint256 _reporterId, bytes calldata _rewardOpts) {
uint256 gasStart = gasleft();
powerPoke.authorizeReporter(_reporterId, msg.sender);
_;
_reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts);
}
modifier onlyNonReporter(uint256 _reporterId, bytes calldata _rewardOpts) {
uint256 gasStart = gasleft();
powerPoke.authorizeNonReporter(_reporterId, msg.sender);
_;
_reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts);
}
constructor(address _piToken, BasicConfig memory _basicConfig) public PowerIndexNaiveRouter() Ownable() {
require(_piToken != address(0), "INVALID_PI_TOKEN");
require(_basicConfig.reserveRatioUpperBound <= HUNDRED_PCT, "UPPER_RR_GREATER_THAN_100_PCT");
require(_basicConfig.reserveRatio >= _basicConfig.reserveRatioLowerBound, "RR_LTE_LOWER_RR");
require(_basicConfig.reserveRatio <= _basicConfig.reserveRatioUpperBound, "RR_GTE_UPPER_RR");
require(_basicConfig.performanceFee < HUNDRED_PCT, "PVP_FEE_GTE_HUNDRED_PCT");
require(_basicConfig.performanceFeeReceiver != address(0), "INVALID_PVP_ADDR");
require(_basicConfig.poolRestrictions != address(0), "INVALID_POOL_RESTRICTIONS_ADDR");
piToken = WrappedPiErc20Interface(_piToken);
(, bytes memory underlyingRes) = _piToken.call(abi.encodeWithSignature("underlying()"));
underlying = IERC20(abi.decode(underlyingRes, (address)));
poolRestrictions = IPoolRestrictions(_basicConfig.poolRestrictions);
powerPoke = IPowerPoke(_basicConfig.powerPoke);
reserveRatio = _basicConfig.reserveRatio;
reserveRatioLowerBound = _basicConfig.reserveRatioLowerBound;
reserveRatioUpperBound = _basicConfig.reserveRatioUpperBound;
claimRewardsInterval = _basicConfig.claimRewardsInterval;
performanceFeeReceiver = _basicConfig.performanceFeeReceiver;
performanceFee = _basicConfig.performanceFee;
}
receive() external payable {}
/*** OWNER METHODS ***/
/**
* @notice Set reserve ratio config
* @param _reserveRatio Share of necessary token balance that piERC20 must hold after poke execution.
* @param _reserveRatioLowerBound Lower bound of ERC20 token balance to force rebalance.
* @param _reserveRatioUpperBound Upper bound of ERC20 token balance to force rebalance.
* @param _claimRewardsInterval Time interval to claim rewards in connectors contracts.
*/
function setReserveConfig(
uint256 _reserveRatio,
uint256 _reserveRatioLowerBound,
uint256 _reserveRatioUpperBound,
uint256 _claimRewardsInterval
) external virtual override onlyOwner {
require(_reserveRatioUpperBound <= HUNDRED_PCT, "UPPER_RR_GREATER_THAN_100_PCT");
require(_reserveRatio >= _reserveRatioLowerBound, "RR_LT_LOWER_RR");
require(_reserveRatio <= _reserveRatioUpperBound, "RR_GT_UPPER_RR");
reserveRatio = _reserveRatio;
reserveRatioLowerBound = _reserveRatioLowerBound;
reserveRatioUpperBound = _reserveRatioUpperBound;
claimRewardsInterval = _claimRewardsInterval;
emit SetReserveConfig(_reserveRatio, _reserveRatioLowerBound, _reserveRatioUpperBound, _claimRewardsInterval);
}
/**
* @notice Set performance fee.
* @param _performanceFee Share of rewards for distributing to performanceFeeReceiver(Protocol treasury).
*/
function setPerformanceFee(uint256 _performanceFee) external onlyOwner {
require(_performanceFee < HUNDRED_PCT, "PERFORMANCE_FEE_OVER_THE_LIMIT");
performanceFee = _performanceFee;
emit SetPerformanceFee(_performanceFee);
}
/**
* @notice Set piERC20 ETH fee for deposit and withdrawal functions.
* @param _ethFee Fee amount in ETH.
*/
function setPiTokenEthFee(uint256 _ethFee) external onlyOwner {
require(_ethFee <= 0.1 ether, "ETH_FEE_OVER_THE_LIMIT");
piToken.setEthFee(_ethFee);
}
/**
* @notice Set connectors configs. Items should have `newConnector` variable to create connectors and `connectorIndex`
* to update existing connectors.
* @param _connectorList Array of connector items.
*/
function setConnectorList(ConnectorInput[] memory _connectorList) external onlyOwner {
require(_connectorList.length != 0, "CONNECTORS_LENGTH_CANT_BE_NULL");
for (uint256 i = 0; i < _connectorList.length; i++) {
ConnectorInput memory c = _connectorList[i];
if (c.newConnector) {
connectors.push(
Connector(
c.connector,
c.share,
c.callBeforeAfterPoke,
0,
0,
new bytes(0),
new bytes(0),
new bytes(0),
new bytes(0)
)
);
c.connectorIndex = connectors.length - 1;
} else {
connectors[c.connectorIndex].connector = c.connector;
connectors[c.connectorIndex].share = c.share;
connectors[c.connectorIndex].callBeforeAfterPoke = c.callBeforeAfterPoke;
}
emit SetConnector(c.connector, c.share, c.callBeforeAfterPoke, c.connectorIndex, c.newConnector);
}
_checkConnectorsTotalShare();
}
/**
* @notice Set connectors claim params to pass it to connector.
* @param _connectorIndex Index of connector
* @param _claimParams Claim params
*/
function setClaimParams(uint256 _connectorIndex, bytes memory _claimParams) external onlyOwner {
connectors[_connectorIndex].claimParams = _claimParams;
emit SetConnectorClaimParams(address(connectors[_connectorIndex].connector), _claimParams);
}
/**
* @notice Set connector stake params to pass it to connector.
* @param _connectorIndex Index of connector
* @param _stakeParams Claim params
*/
function setStakeParams(uint256 _connectorIndex, bytes memory _stakeParams) external onlyOwner {
connectors[_connectorIndex].stakeParams = _stakeParams;
emit SetConnectorStakeParams(address(connectors[_connectorIndex].connector), _stakeParams);
}
/**
* @notice Set piERC20 noFee config for account address.
* @param _for Account address.
* @param _noFee Value for account.
*/
function setPiTokenNoFee(address _for, bool _noFee) external onlyOwner {
piToken.setNoFee(_for, _noFee);
}
/**
* @notice Call piERC20 `withdrawEthFee`.
* @param _receiver Receiver address.
*/
function withdrawEthFee(address payable _receiver) external onlyOwner {
piToken.withdrawEthFee(_receiver);
}
/**
* @notice Transfer ERC20 balances and rights to a new router address.
* @param _piToken piERC20 address.
* @param _newRouter New router contract address.
* @param _tokens ERC20 to transfer.
*/
function migrateToNewRouter(
address _piToken,
address payable _newRouter,
address[] memory _tokens
) public override onlyOwner {
super.migrateToNewRouter(_piToken, _newRouter, _tokens);
_newRouter.transfer(address(this).balance);
uint256 len = _tokens.length;
for (uint256 i = 0; i < len; i++) {
IERC20 t = IERC20(_tokens[i]);
t.safeTransfer(_newRouter, t.balanceOf(address(this)));
}
}
/**
* @notice Call initRouter function of the connector contract.
* @param _connectorIndex Connector index in connectors array.
* @param _data To pass as an argument.
*/
function initRouterByConnector(uint256 _connectorIndex, bytes memory _data) public onlyOwner {
(bool success, bytes memory result) = address(connectors[_connectorIndex].connector).delegatecall(
abi.encodeWithSignature("initRouter(bytes)", _data)
);
require(success, string(result));
}
/**
* @notice Call poke by Reporter.
* @param _reporterId Reporter ID.
* @param _claimAndDistributeRewards Claim rewards only if interval reached.
* @param _rewardOpts To whom and how to reward Reporter.
*/
function pokeFromReporter(
uint256 _reporterId,
bool _claimAndDistributeRewards,
bytes calldata _rewardOpts
) external onlyReporter(_reporterId, _rewardOpts) onlyEOA {
_pokeFrom(_claimAndDistributeRewards, false);
}
/**
* @notice Call poke by Slasher.
* @param _reporterId Slasher ID.
* @param _claimAndDistributeRewards Claim rewards only if interval reached.
* @param _rewardOpts To whom and how reward Slasher.
*/
function pokeFromSlasher(
uint256 _reporterId,
bool _claimAndDistributeRewards,
bytes calldata _rewardOpts
) external onlyNonReporter(_reporterId, _rewardOpts) onlyEOA {
_pokeFrom(_claimAndDistributeRewards, true);
}
/**
* @notice Executes rebalance(beforePoke, rebalancePoke, claimRewards, afterPoke) for connector contract by config.
* @param _conf Connector rebalance config.
*/
function _rebalancePokeByConf(RebalanceConfig memory _conf) internal {
Connector storage c = connectors[_conf.connectorIndex];
if (c.callBeforeAfterPoke) {
_beforePoke(c, _conf.shouldClaim);
}
if (_conf.status != StakeStatus.EQUILIBRIUM) {
_rebalancePoke(c, _conf.status, _conf.diff);
}
// check claim interval again due to possibility of claiming by stake or redeem function(maybe already claimed)
if (_conf.shouldClaim && claimRewardsIntervalReached(c.lastClaimRewardsAt)) {
_claimRewards(c, _conf.status);
c.lastClaimRewardsAt = block.timestamp;
} else {
require(_conf.status != StakeStatus.EQUILIBRIUM, "NOTHING_TO_DO");
}
if (c.callBeforeAfterPoke) {
_afterPoke(c, _conf.status, _conf.shouldClaim);
}
}
function claimRewardsIntervalReached(uint256 _lastClaimRewardsAt) public view returns (bool) {
return _lastClaimRewardsAt + claimRewardsInterval < block.timestamp;
}
/**
* @notice Rebalance every connector according to its share in an array.
* @param _claimAndDistributeRewards Need to claim and distribute rewards.
* @param _isSlasher Calling by Slasher.
*/
function _pokeFrom(bool _claimAndDistributeRewards, bool _isSlasher) internal {
PokeFromState memory state = PokeFromState(0, 0, 0, false);
(state.minInterval, state.maxInterval) = _getMinMaxReportInterval();
state.piTokenUnderlyingBalance = piToken.getUnderlyingBalance();
(uint256[] memory stakedBalanceList, uint256 totalStakedBalance) = _getUnderlyingStakedList();
state.atLeastOneForceRebalance = false;
RebalanceConfig[] memory configs = new RebalanceConfig[](connectors.length);
// First cycle: connectors with EXCESS balance status on staking
for (uint256 i = 0; i < connectors.length; i++) {
if (connectors[i].share == 0) {
continue;
}
(StakeStatus status, uint256 diff, bool shouldClaim, bool forceRebalance) = getStakeAndClaimStatus(
state.piTokenUnderlyingBalance,
totalStakedBalance,
stakedBalanceList[i],
_claimAndDistributeRewards,
connectors[i]
);
if (forceRebalance) {
state.atLeastOneForceRebalance = true;
}
if (status == StakeStatus.EXCESS) {
// Calling rebalance immediately if interval conditions reached
if (_canPoke(_isSlasher, forceRebalance, state.minInterval, state.maxInterval)) {
_rebalancePokeByConf(RebalanceConfig(false, status, diff, shouldClaim, forceRebalance, i));
}
} else {
// Push config for second cycle
configs[i] = RebalanceConfig(true, status, diff, shouldClaim, forceRebalance, i);
}
}
require(
_canPoke(_isSlasher, state.atLeastOneForceRebalance, state.minInterval, state.maxInterval),
"INTERVAL_NOT_REACHED_OR_NOT_FORCE"
);
// Second cycle: connectors with EQUILIBRIUM and SHORTAGE balance status on staking
for (uint256 i = 0; i < connectors.length; i++) {
if (!configs[i].shouldPushFunds) {
continue;
}
// Calling rebalance if interval conditions reached
if (_canPoke(_isSlasher, configs[i].forceRebalance, state.minInterval, state.maxInterval)) {
_rebalancePokeByConf(configs[i]);
}
}
lastRebalancedAt = block.timestamp;
}
/**
* @notice Checking: if time interval reached or have `forceRebalance`.
*/
function _canPoke(
bool _isSlasher,
bool _forceRebalance,
uint256 _minInterval,
uint256 _maxInterval
) internal view returns (bool) {
if (_forceRebalance) {
return true;
}
return
_isSlasher
? (lastRebalancedAt + _maxInterval < block.timestamp)
: (lastRebalancedAt + _minInterval < block.timestamp);
}
/**
* @notice Call redeem in the connector with delegatecall, save result stakeData if not null.
*/
function _redeem(Connector storage _c, uint256 _diff) internal {
_callStakeRedeem("redeem(uint256,(bytes,bytes,uint256,address))", _c, _diff);
}
/**
* @notice Call stake in the connector with delegatecall, save result `stakeData` if not null.
*/
function _stake(Connector storage _c, uint256 _diff) internal {
_callStakeRedeem("stake(uint256,(bytes,bytes,uint256,address))", _c, _diff);
}
function _callStakeRedeem(
string memory _method,
Connector storage _c,
uint256 _diff
) internal {
(bool success, bytes memory result) = address(_c.connector).delegatecall(
abi.encodeWithSignature(_method, _diff, _getDistributeData(_c))
);
require(success, string(result));
bool claimed;
(result, claimed) = abi.decode(result, (bytes, bool));
if (result.length > 0) {
_c.stakeData = result;
}
if (claimed) {
_c.lastClaimRewardsAt = block.timestamp;
}
_c.lastChangeStakeAt = block.timestamp;
}
/**
* @notice Call `beforePoke` in the connector with delegatecall, do not save `pokeData`.
*/
function _beforePoke(Connector storage c, bool _willClaimReward) internal {
(bool success, ) = address(c.connector).delegatecall(
abi.encodeWithSignature(
"beforePoke(bytes,(bytes,uint256,address),bool)",
c.pokeData,
_getDistributeData(c),
_willClaimReward
)
);
require(success, "_beforePoke call error");
}
/**
* @notice Call `afterPoke` in the connector with delegatecall, save result `pokeData` if not null.
*/
function _afterPoke(
Connector storage _c,
StakeStatus _stakeStatus,
bool _rewardClaimDone
) internal {
(bool success, bytes memory result) = address(_c.connector).delegatecall(
abi.encodeWithSignature("afterPoke(uint8,bool)", uint8(_stakeStatus), _rewardClaimDone)
);
require(success, string(result));
result = abi.decode(result, (bytes));
if (result.length > 0) {
_c.pokeData = result;
}
}
/**
* @notice Rebalance connector: stake if StakeStatus.SHORTAGE and redeem if StakeStatus.EXCESS.
*/
function _rebalancePoke(
Connector storage _c,
StakeStatus _stakeStatus,
uint256 _diff
) internal {
if (_stakeStatus == StakeStatus.EXCESS) {
_redeem(_c, _diff);
} else if (_stakeStatus == StakeStatus.SHORTAGE) {
_stake(_c, _diff);
}
}
function redeem(uint256 _connectorIndex, uint256 _diff) external onlyOwner {
_redeem(connectors[_connectorIndex], _diff);
}
function stake(uint256 _connectorIndex, uint256 _diff) external onlyOwner {
_stake(connectors[_connectorIndex], _diff);
}
/**
* @notice Explicitly collects the assigned rewards. If a reward token is the same as the underlying, it should
* allocate it at piERC20. Otherwise, it should transfer to the router contract for further action.
* @dev It's not the only way to claim rewards. Sometimes rewards are distributed implicitly while interacting
* with a protocol. E.g., MasterChef distributes rewards on each `deposit()/withdraw()` action, and there is
* no use in calling `_claimRewards()` immediately after calling one of these methods.
*/
function _claimRewards(Connector storage c, StakeStatus _stakeStatus) internal {
(bool success, bytes memory result) = address(c.connector).delegatecall(
abi.encodeWithSelector(IRouterConnector.claimRewards.selector, _stakeStatus, _getDistributeData(c))
);
require(success, string(result));
result = abi.decode(result, (bytes));
if (result.length > 0) {
c.stakeData = result;
}
}
function _reward(
uint256 _reporterId,
uint256 _gasStart,
uint256 _compensationPlan,
bytes calldata _rewardOpts
) internal {
powerPoke.reward(_reporterId, _gasStart.sub(gasleft()), _compensationPlan, _rewardOpts);
}
/*
* @dev Getting status and diff of actual staked balance and target reserve balance.
*/
function getStakeStatusForBalance(uint256 _stakedBalance, uint256 _share)
external
view
returns (
StakeStatus status,
uint256 diff,
bool forceRebalance
)
{
return getStakeStatus(piToken.getUnderlyingBalance(), getUnderlyingStaked(), _stakedBalance, _share);
}
function getStakeAndClaimStatus(
uint256 _leftOnPiTokenBalance,
uint256 _totalStakedBalance,
uint256 _stakedBalance,
bool _claimAndDistributeRewards,
Connector memory _c
)
public
view
returns (
StakeStatus status,
uint256 diff,
bool shouldClaim,
bool forceRebalance
)
{
(status, diff, forceRebalance) = getStakeStatus(
_leftOnPiTokenBalance,
_totalStakedBalance,
_stakedBalance,
_c.share
);
shouldClaim = _claimAndDistributeRewards && claimRewardsIntervalReached(_c.lastClaimRewardsAt);
if (shouldClaim && _c.claimParams.length != 0) {
shouldClaim = _c.connector.isClaimAvailable(_c.claimParams, _c.lastClaimRewardsAt, _c.lastChangeStakeAt);
if (shouldClaim && !forceRebalance) {
forceRebalance = true;
}
}
}
/*
* @dev Getting status and diff of current staked balance and target stake balance.
*/
function getStakeStatus(
uint256 _leftOnPiTokenBalance,
uint256 _totalStakedBalance,
uint256 _stakedBalance,
uint256 _share
)
public
view
returns (
StakeStatus status,
uint256 diff,
bool forceRebalance
)
{
uint256 expectedStakeAmount;
(status, diff, expectedStakeAmount) = getStakeStatusPure(
reserveRatio,
_leftOnPiTokenBalance,
_totalStakedBalance,
_stakedBalance,
_share
);
if (status == StakeStatus.EQUILIBRIUM) {
return (status, diff, forceRebalance);
}
uint256 denominator = _leftOnPiTokenBalance.add(_totalStakedBalance);
if (status == StakeStatus.EXCESS) {
uint256 numerator = _leftOnPiTokenBalance.add(diff).mul(HUNDRED_PCT);
uint256 currentRatio = numerator.div(denominator);
forceRebalance = reserveRatioLowerBound >= currentRatio;
} else if (status == StakeStatus.SHORTAGE) {
if (diff > _leftOnPiTokenBalance) {
return (status, diff, true);
}
uint256 numerator = _leftOnPiTokenBalance.sub(diff).mul(HUNDRED_PCT);
uint256 currentRatio = numerator.div(denominator);
forceRebalance = reserveRatioUpperBound <= currentRatio;
}
}
function getUnderlyingStaked() public view virtual returns (uint256) {
uint256 underlyingStaked = 0;
for (uint256 i = 0; i < connectors.length; i++) {
require(address(connectors[i].connector) != address(0), "CONNECTOR_IS_NULL");
underlyingStaked += connectors[i].connector.getUnderlyingStaked();
}
return underlyingStaked;
}
function _getUnderlyingStakedList() internal view virtual returns (uint256[] memory list, uint256 total) {
uint256[] memory underlyingStakedList = new uint256[](connectors.length);
total = 0;
for (uint256 i = 0; i < connectors.length; i++) {
require(address(connectors[i].connector) != address(0), "CONNECTOR_IS_NULL");
underlyingStakedList[i] = connectors[i].connector.getUnderlyingStaked();
total += underlyingStakedList[i];
}
return (underlyingStakedList, total);
}
function getUnderlyingReserve() public view returns (uint256) {
return underlying.balanceOf(address(piToken));
}
function calculateLockedProfit() public view returns (uint256) {
uint256 lockedProfit = 0;
for (uint256 i = 0; i < connectors.length; i++) {
require(address(connectors[i].connector) != address(0), "CONNECTOR_IS_NULL");
lockedProfit += connectors[i].connector.calculateLockedProfit(connectors[i].stakeData);
}
return lockedProfit;
}
function getUnderlyingAvailable() public view returns (uint256) {
// _getUnderlyingReserve + getUnderlyingStaked - _calculateLockedProfit
return getUnderlyingReserve().add(getUnderlyingStaked()).sub(calculateLockedProfit());
}
function getUnderlyingTotal() external view returns (uint256) {
// _getUnderlyingReserve + getUnderlyingStaked
return getUnderlyingReserve().add(getUnderlyingStaked());
}
function getPiEquivalentForUnderlying(uint256 _underlyingAmount, uint256 _piTotalSupply)
external
view
virtual
override
returns (uint256)
{
return getPiEquivalentForUnderlyingPure(_underlyingAmount, getUnderlyingAvailable(), _piTotalSupply);
}
function getPiEquivalentForUnderlyingPure(
uint256 _underlyingAmount,
uint256 _totalUnderlyingWrapped,
uint256 _piTotalSupply
) public pure virtual override returns (uint256) {
if (_piTotalSupply == 0) {
return _underlyingAmount;
}
// return _piTotalSupply * _underlyingAmount / _totalUnderlyingWrapped;
return _piTotalSupply.mul(_underlyingAmount).div(_totalUnderlyingWrapped);
}
function getUnderlyingEquivalentForPi(uint256 _piAmount, uint256 _piTotalSupply)
external
view
virtual
override
returns (uint256)
{
return getUnderlyingEquivalentForPiPure(_piAmount, getUnderlyingAvailable(), _piTotalSupply);
}
function getUnderlyingEquivalentForPiPure(
uint256 _piAmount,
uint256 _totalUnderlyingWrapped,
uint256 _piTotalSupply
) public pure virtual override returns (uint256) {
if (_piTotalSupply == 0) {
return _piAmount;
}
// _piAmount * _totalUnderlyingWrapped / _piTotalSupply;
return _totalUnderlyingWrapped.mul(_piAmount).div(_piTotalSupply);
}
/**
* @notice Calculates the desired stake status.
* @param _reserveRatioPct The reserve ratio in %, 1 ether == 100 ether.
* @param _leftOnPiToken The underlying ERC20 tokens balance on the piERC20 contract.
* @param _totalStakedBalance The underlying ERC20 tokens balance staked on the all connected staking contracts.
* @param _stakedBalance The underlying ERC20 tokens balance staked on the connector staking contract.
* @param _share Share of the connector contract.
* @return status The stake status:
* * SHORTAGE: There is not enough underlying ERC20 balance on the staking contract to satisfy the reserve ratio.
* Therefore, the connector contract should send the diff amount to the staking contract.
* * EXCESS: There is some extra underlying ERC20 balance on the staking contract.
* Therefore, the connector contract should redeem the diff amount from the staking contract.
* * EQUILIBRIUM: The reserve ratio hasn't changed, the diff amount is 0, and no need for additional
* stake/redeem actions.
* @return diff The difference between `expectedStakeAmount` and `_stakedBalance`.
* @return expectedStakeAmount The calculated expected underlying ERC20 staked balance.
*/
function getStakeStatusPure(
uint256 _reserveRatioPct,
uint256 _leftOnPiToken,
uint256 _totalStakedBalance,
uint256 _stakedBalance,
uint256 _share
)
public
view
returns (
StakeStatus status,
uint256 diff,
uint256 expectedStakeAmount
)
{
require(_reserveRatioPct <= HUNDRED_PCT, "RR_GREATER_THAN_100_PCT");
expectedStakeAmount = getExpectedStakeAmount(_reserveRatioPct, _leftOnPiToken, _totalStakedBalance, _share);
if (expectedStakeAmount > _stakedBalance) {
status = StakeStatus.SHORTAGE;
diff = expectedStakeAmount.sub(_stakedBalance);
} else if (expectedStakeAmount < _stakedBalance) {
status = StakeStatus.EXCESS;
diff = _stakedBalance.sub(expectedStakeAmount);
} else {
status = StakeStatus.EQUILIBRIUM;
diff = 0;
}
}
/**
* @notice Calculates an expected underlying ERC20 staked balance.
* @param _reserveRatioPct % of a reserve ratio, 1 ether == 100%.
* @param _leftOnPiToken The underlying ERC20 tokens balance on the piERC20 contract.
* @param _stakedBalance The underlying ERC20 tokens balance staked on the staking contract.
* @param _share % of a total connectors share, 1 ether == 100%.
* @return expectedStakeAmount The expected stake amount:
*
* / (100% - %reserveRatio) * (_leftOnPiToken + _stakedBalance) * %share \
* expectedStakeAmount = | ----------------------------------------------------------------------|
* \ 100% /
*/
function getExpectedStakeAmount(
uint256 _reserveRatioPct,
uint256 _leftOnPiToken,
uint256 _stakedBalance,
uint256 _share
) public pure returns (uint256) {
return
uint256(1 ether).sub(_reserveRatioPct).mul(_stakedBalance.add(_leftOnPiToken).mul(_share).div(HUNDRED_PCT)).div(
HUNDRED_PCT
);
}
function _getMinMaxReportInterval() internal view returns (uint256 min, uint256 max) {
return powerPoke.getMinMaxReportIntervals(address(this));
}
function _getDistributeData(Connector storage c) internal view returns (IRouterConnector.DistributeData memory) {
return IRouterConnector.DistributeData(c.stakeData, c.stakeParams, performanceFee, performanceFeeReceiver);
}
function _checkConnectorsTotalShare() internal view {
uint256 totalShare = 0;
for (uint256 i = 0; i < connectors.length; i++) {
require(address(connectors[i].connector) != address(0), "CONNECTOR_IS_NULL");
totalShare = totalShare.add(connectors[i].share);
}
require(totalShare == HUNDRED_PCT, "TOTAL_SHARE_IS_NOT_HUNDRED_PCT");
}
}
| Explicitly collects the assigned rewards. If a reward token is the same as the underlying, it should allocate it at piERC20. Otherwise, it should transfer to the router contract for further action. It's not the only way to claim rewards. Sometimes rewards are distributed implicitly while interacting with a protocol. E.g., MasterChef distributes rewards on each `deposit()/withdraw()` action, and there is no use in calling `_claimRewards()` immediately after calling one of these methods./ | function _claimRewards(Connector storage c, StakeStatus _stakeStatus) internal {
(bool success, bytes memory result) = address(c.connector).delegatecall(
abi.encodeWithSelector(IRouterConnector.claimRewards.selector, _stakeStatus, _getDistributeData(c))
);
require(success, string(result));
result = abi.decode(result, (bytes));
if (result.length > 0) {
c.stakeData = result;
}
}
| 5,362,852 |
// SPDX-License-Identifier: SimPL-2.0
pragma solidity 0.6.12;
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) {
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) {
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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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 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));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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));
}
}
interface IMigrator {
function migrate(IERC20 token) external returns (IERC20);
}
interface IAward {
function addFreeAward(address _user, uint256 _amount) external;
function addAward(address _user, uint256 _amount) external;
function withdraw(uint256 _amount) external;
function destroy(uint256 amount) external;
}
contract LPStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 lockRewards; // lock rewards when not migrated
uint256 stakeBlocks; // number of blocks containing staking;
uint256 lastBlock; // the last block.number when update shares;
uint256 accStakeShares; // accumulate stakes: ∑(amount * stakeBlocks);
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Token to distribute per block.
uint256 lastRewardBlock; // Last block number that Token distribution occurs.
uint256 accTokenPerShare; // Accumulated Token per share, times 1e12. See below.
}
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigrator public migrator;
// The block number when Token mining starts.
uint256 immutable public startBlock;
// The block number when Token mining ends.
uint256 immutable public endBlock;
// Reward token created per block.
uint256 public tokenPerBlock = 755 * 10 ** 16;
mapping(address => bool) public poolIn;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
bool public migrated;
IAward award;
event Add(uint256 allocPoint, address lpToken, bool withUpdate);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetMigrator(address indexed newMigrator);
event Migrate(uint256 pid, address indexed lpToken, address indexed newToken);
event Initialization(address award, uint256 tokenPerBlock, uint256 startBlock, uint256 endBlock);
event Set(uint256 pid, uint256 allocPoint, bool withUpdate);
event UpdatePool(uint256 pid, uint256 accTokenPerShare, uint256 lastRewardBlock);
constructor(
IAward _award,
uint256 _tokenPerBlock,
uint256 _startBlock,
uint256 _endBlock
) public {
require(_startBlock < _endBlock, "LPStaking: invalid block range");
award = _award;
tokenPerBlock = _tokenPerBlock;
startBlock = _startBlock;
endBlock = _endBlock;
emit Initialization(address(_award), _tokenPerBlock, _startBlock, _endBlock);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, address _lpToken, bool _withUpdate) public onlyOwner {
require(!poolIn[_lpToken], "LPStaking: duplicate lpToken");
if (_withUpdate) {
batchUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken : IERC20(_lpToken),
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accTokenPerShare : 0
}));
poolIn[_lpToken] = true;
emit Add(_allocPoint, _lpToken, _withUpdate);
}
// Update the given pool's Token allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
if (_withUpdate) {
batchUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
emit Set(_pid, _allocPoint, _withUpdate);
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigrator _migrator) public onlyOwner {
migrator = _migrator;
emit SetMigrator(address(_migrator));
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
emit Migrate(_pid, address(lpToken), address(newLpToken));
}
function setMigrated() onlyOwner public {
migrated = true;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) private view returns (uint256) {
if (_to <= endBlock) {
return _to.sub(_from);
} else if (_from >= endBlock) {
return 0;
} else {
return endBlock.sub(_from);
}
}
// View function to see pending Token on frontend.
function pendingShares(uint256 _pid, address _user) external view returns (uint256) {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewards = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accTokenPerShare = accTokenPerShare.add(rewards.mul(1e12).div(lpSupply));
}
return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function batchUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
PoolInfo storage pool = poolInfo[_pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
} else {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewards = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accTokenPerShare = pool.accTokenPerShare.add(rewards.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
}
emit UpdatePool(_pid, pool.accTokenPerShare, pool.lastRewardBlock);
}
function shareAwards(uint256 _pid) private {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = 0;
if (user.amount > 0) {
pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);
uint256 num = block.number - user.lastBlock;
user.stakeBlocks = user.stakeBlocks.add(num);
user.accStakeShares = user.accStakeShares.add(user.amount.mul(num));
}
if (migrated) {
uint256 locked = user.lockRewards.add(pending);
user.lockRewards = 0;
uint256 audit = user.stakeBlocks.mul(user.amount);
if (user.accStakeShares > audit) {
uint256 _locked = locked.mul(audit).div(user.accStakeShares);
award.destroy(locked.sub(_locked));
locked = _locked;
}
if (locked > 0) {
award.addAward(msg.sender, locked);
}
} else {
user.lockRewards = user.lockRewards.add(pending);
}
user.lastBlock = block.number;
}
// Deposit LP tokens to Staking for shares allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
shareAwards(_pid);
pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from LPStaking.
function withdraw(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
shareAwards(_pid);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
pool.lpToken.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(msg.sender, user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
} | Deposit LP tokens to Staking for shares allocation. | function deposit(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, "LPStaking: pool index overflow");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
shareAwards(_pid);
pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 5,871,112 |
./full_match/3/0x558aA5DF498bc8A889425aA1F73D9Cac2605c88b/sources/github/alexanderpetrov-sudo/sorry.finance/contract/SORRYFinance_6.0.sol | Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./ | function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| 8,114,584 |
./full_match/80001/0x18598e5E600537dc21FA0A5a337b81a294F86633/sources/contracts/AdventurePermissions.sol | Removes an adventure from the whitelist | function unwhitelistAdventure(address adventure) external onlyOwner {
require(whitelistedAdventures[adventure].isWhitelisted, "Not whitelisted");
uint128 itemPositionToDelete = whitelistedAdventures[adventure].arrayIndex;
whitelistedAdventureList[itemPositionToDelete] = whitelistedAdventureList[whitelistedAdventureList.length - 1];
whitelistedAdventures[whitelistedAdventureList[itemPositionToDelete]].arrayIndex = itemPositionToDelete;
whitelistedAdventureList.pop();
delete whitelistedAdventures[adventure];
emit AdventureWhitelistUpdated(adventure, false);
}
| 834,568 |
./partial_match/1/0x8D01673640F698D45FEc7f700aeaB7535Cc92c0F/sources/HOPE20.sol | generate the uniswap pair path of token -> weth make the swap | function swapTokenAmountEth(uint256 amount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), amount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
path,
address(this),
block.timestamp
);
receive() external payable {}
}
| 4,181,867 |
./partial_match/1/0x7D1f2DC0876776d12F7Aee6c18f16b41C175744D/sources/HARVEY.sol | Enable and disable backend fees/ | function setFeeState(bool state) external teamOROwner {
feesDisabled = state;
}
| 16,040,497 |
./partial_match/97/0x379e2e114831EAD94446e6A6509fA25Fea1005b5/sources/CFD.sol | if overnight fee rate is positive, traders with long position pay traders with short position and vice versa. _exchange IExchange address/ | function payOvernightFee(IExchange _exchange) external {
requireExchange(_exchange, true);
systemSettings.setNextOvernightFeeTime(_exchange);
Decimal.decimal memory overnightFeeRate = systemSettings.overnightFeeRatio();
exchangeMap[address(_exchange)].cumulativeOvernightFeerates.push(
overnightFeeRate.addD(getLatestCumulativeOvernightFeeRate(_exchange))
);
Decimal.decimal memory totalOpenNotional = exchangeMap[address(_exchange)].totalOpenNotional;
Decimal.decimal memory exchageOvernightPayment = overnightFeeRate.mulD(totalOpenNotional);
if (exchageOvernightPayment.toUint() > 0) {
address insuranceFundAddress = address(systemSettings.getInsuranceFund(_exchange));
require(insuranceFundAddress != address(0), "Invalid InsuranceFund");
Decimal.decimal memory insuranceFundFee =
exchageOvernightPayment.mulD(systemSettings.overnightFeeLpShareRatio());
cfdVault.withdraw(_exchange.quoteAsset(), insuranceFundAddress, insuranceFundFee);
Decimal.decimal memory overnightFee = exchageOvernightPayment.subD(insuranceFundFee);
cfdVault.addCachedLiquidity(_exchange, overnightFee);
}
emit OvernightFeePayed(
address(_exchange),
totalOpenNotional.toUint(),
exchageOvernightPayment.toUint(),
overnightFeeRate.toUint()
);
}
| 11,473,198 |
pragma solidity ^0.4.21;
/// @title ERC-165 Standard Interface Detection
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/**
* @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 ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
contract ERC721 is ERC165 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard
interface ERC721TokenReceiver {
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
interface ERC721Metadata /* is ERC721 */ {
function name() external pure returns (string _name);
function symbol() external pure returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
interface ERC721Enumerable /* is ERC721 */ {
function totalSupply() external view returns (uint256);
function tokenByIndex(uint256 _index) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// @title A reusable contract to comply with ERC-165
/// @author William Entriken (https://phor.net)
contract PublishInterfaces is ERC165 {
/// @dev Every interface that we support
mapping(bytes4 => bool) internal supportedInterfaces;
function PublishInterfaces() internal {
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return supportedInterfaces[interfaceID] && (interfaceID != 0xffffffff);
}
}
/// @title The external contract that is responsible for generating metadata for GanTokens,
/// it has one function that will return the data as bytes.
contract Metadata {
/// @dev Given a token Id, returns a string with metadata
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
contract GanNFT is ERC165, ERC721, ERC721Enumerable, PublishInterfaces, Ownable {
function GanNFT() internal {
supportedInterfaces[0x80ac58cd] = true; // ERC721
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
supportedInterfaces[0x8153916a] = true; // ERC721 + 165 (not needed)
}
bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
// @dev claim price taken for each new GanToken
// generating a new token will be free in the beinging and later changed
uint256 public claimPrice = 0;
// @dev max supply for token
uint256 public maxSupply = 300;
// The contract that will return tokens metadata
Metadata public erc721Metadata;
/// @dev list of all owned token ids
uint256[] public tokenIds;
/// @dev a mpping for all tokens
mapping(uint256 => address) public tokenIdToOwner;
/// @dev mapping to keep owner balances
mapping(address => uint256) public ownershipCounts;
/// @dev mapping to owners to an array of tokens that they own
mapping(address => uint256[]) public ownerBank;
/// @dev mapping to approved ids
mapping(uint256 => address) public tokenApprovals;
/// @dev The authorized operators for each address
mapping (address => mapping (address => bool)) internal operatorApprovals;
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure returns (string) {
return "GanToken";
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure returns (string) {
return "GT";
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// Only the contract creater can call this.
/// @param _contractAddress The location of the contract with meta data
function setMetadataAddress(address _contractAddress) public onlyOwner {
erc721Metadata = Metadata(_contractAddress);
}
modifier canTransfer(uint256 _tokenId, address _from, address _to) {
address owner = tokenIdToOwner[_tokenId];
require(tokenApprovals[_tokenId] == _to || owner == _from || operatorApprovals[_to][_to]);
_;
}
/// @notice checks to see if a sender owns a _tokenId
/// @param _tokenId The identifier for an NFT
modifier owns(uint256 _tokenId) {
require(tokenIdToOwner[_tokenId] == msg.sender);
_;
}
/// @dev This emits any time the ownership of a GanToken changes.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/// @dev This emits when the approved addresses for a GanToken is changed or reaffirmed.
/// The zero address indicates there is no owner and it get reset on a transfer
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice allow the owner to set the supply max
function setMaxSupply(uint max) external payable onlyOwner {
require(max > tokenIds.length);
maxSupply = max;
}
/// @notice allow the owner to set a new fee for creating a GanToken
function setClaimPrice(uint256 price) external payable onlyOwner {
claimPrice = price;
}
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) external view returns (uint256 balance) {
balance = ownershipCounts[_owner];
}
/// @notice Gets the onwner of a an NFT
/// @param _tokenId The identifier for an NFT
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = tokenIdToOwner[_tokenId];
}
/// @notice returns all owners' tokens will return an empty array
/// if the address has no tokens
/// @param _owner The address of the owner in question
function tokensOfOwner(address _owner) external view returns (uint256[]) {
uint256 tokenCount = ownershipCounts[_owner];
if (tokenCount == 0) {
return new uint256[](0);
}
uint256[] memory result = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
result[i] = ownerBank[_owner][i];
}
return result;
}
/// @dev creates a list of all the tokenIds
function getAllTokenIds() external view returns (uint256[]) {
uint256[] memory result = new uint256[](tokenIds.length);
for (uint i = 0; i < result.length; i++) {
result[i] = tokenIds[i];
}
return result;
}
/// @notice Create a new GanToken with a id and attaches an owner
/// @param _noise The id of the token that's being created
function newGanToken(uint256 _noise) external payable {
require(msg.sender != address(0));
require(tokenIdToOwner[_noise] == 0x0);
require(tokenIds.length < maxSupply);
require(msg.value >= claimPrice);
tokenIds.push(_noise);
ownerBank[msg.sender].push(_noise);
tokenIdToOwner[_noise] = msg.sender;
ownershipCounts[msg.sender]++;
emit Transfer(address(0), msg.sender, 0);
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable
{
_safeTransferFrom(_from, _to, _tokenId, data);
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to ""
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable {
require(_to != 0x0);
require(_to != address(this));
require(tokenApprovals[_tokenId] == msg.sender);
require(tokenIdToOwner[_tokenId] == _from);
_transfer(_tokenId, _to);
}
/// @notice Grant another address the right to transfer a specific token via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @dev Required for ERC-721 compliance.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
function approve(address _to, uint256 _tokenId) external owns(_tokenId) payable {
// Register the approval (replacing any previous approval).
tokenApprovals[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all your asset.
/// @dev Emits the ApprovalForAll event
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operators is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external {
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Get the approved address for a single NFT
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address) {
return tokenApprovals[_tokenId];
}
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
/// @dev Required for ERC-721 compliance.
function totalSupply() external view returns (uint256) {
return tokenIds.length;
}
/// @notice Enumerate valid NFTs
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for index the `_index`th NFT 0 if it doesn't exist,
function tokenByIndex(uint256 _index) external view returns (uint256) {
return tokenIds[_index];
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) {
require(_owner != address(0));
require(_index < ownerBank[_owner].length);
_tokenId = ownerBank[_owner][_index];
}
function _transfer(uint256 _tokenId, address _to) internal {
require(_to != address(0));
address from = tokenIdToOwner[_tokenId];
uint256 tokenCount = ownershipCounts[from];
// remove from ownerBank and replace the deleted token id
for (uint256 i = 0; i < tokenCount; i++) {
uint256 ownedId = ownerBank[from][i];
if (_tokenId == ownedId) {
delete ownerBank[from][i];
if (i != tokenCount) {
ownerBank[from][i] = ownerBank[from][tokenCount - 1];
}
break;
}
}
ownershipCounts[from]--;
ownershipCounts[_to]++;
ownerBank[_to].push(_tokenId);
tokenIdToOwner[_tokenId] = _to;
tokenApprovals[_tokenId] = address(0);
emit Transfer(from, _to, 1);
}
/// @dev Actually perform the safeTransferFrom
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)
private
canTransfer(_tokenId, _from, _to)
{
address owner = tokenIdToOwner[_tokenId];
require(owner == _from);
require(_to != address(0));
require(_to != address(this));
_transfer(_tokenId, _to);
// Do the callback after everything is done to avoid reentrancy attack
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if (codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
require(retval == ERC721_RECEIVED);
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b4a7b4b6bdbbbcb195bbbaa1b1baa1fbbbb0a1">[email protected]</a>>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private pure {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0c3d0d2d9dfd8d5f1dfdec5d5dec59fdfd4c5">[email protected]</a>>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) {
string memory outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the GanToken whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
uint256 count;
bytes32[4] memory buffer;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
contract GanTokenMain is GanNFT {
struct Offer {
bool isForSale;
uint256 tokenId;
address seller;
uint value; // in ether
address onlySellTo; // specify to sell only to a specific person
}
struct Bid {
bool hasBid;
uint256 tokenId;
address bidder;
uint value;
}
/// @dev mapping of balances for address
mapping(address => uint256) public pendingWithdrawals;
/// @dev mapping of tokenId to to an offer
mapping(uint256 => Offer) public ganTokenOfferedForSale;
/// @dev mapping bids to tokenIds
mapping(uint256 => Bid) public tokenBids;
event BidForGanTokenOffered(uint256 tokenId, uint256 value, address sender);
event BidWithdrawn(uint256 tokenId, uint256 value, address bidder);
event GanTokenOfferedForSale(uint256 tokenId, uint256 minSalePriceInWei, address onlySellTo);
event GanTokenNoLongerForSale(uint256 tokenId);
/// @notice Allow a token owner to pull sale
/// @param tokenId The id of the token that's created
function ganTokenNoLongerForSale(uint256 tokenId) public payable owns(tokenId) {
ganTokenOfferedForSale[tokenId] = Offer(false, tokenId, msg.sender, 0, 0x0);
emit GanTokenNoLongerForSale(tokenId);
}
/// @notice Put a token up for sale
/// @param tokenId The id of the token that's created
/// @param minSalePriceInWei desired price of token
function offerGanTokenForSale(uint tokenId, uint256 minSalePriceInWei) external payable owns(tokenId) {
ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, 0x0);
emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, 0x0);
}
/// @notice Create a new GanToken with a id and attaches an owner
/// @param tokenId The id of the token that's being created
function offerGanTokenForSaleToAddress(uint tokenId, address sendTo, uint256 minSalePriceInWei) external payable {
require(tokenIdToOwner[tokenId] == msg.sender);
ganTokenOfferedForSale[tokenId] = Offer(true, tokenId, msg.sender, minSalePriceInWei, sendTo);
emit GanTokenOfferedForSale(tokenId, minSalePriceInWei, sendTo);
}
/// @notice Allows an account to buy a NFT gan token that is up for offer
/// the token owner must set onlySellTo to the sender
/// @param id the id of the token
function buyGanToken(uint256 id) public payable {
Offer memory offer = ganTokenOfferedForSale[id];
require(offer.isForSale);
require(offer.onlySellTo == msg.sender && offer.onlySellTo != 0x0);
require(msg.value == offer.value);
require(tokenIdToOwner[id] == offer.seller);
safeTransferFrom(offer.seller, offer.onlySellTo, id);
ganTokenOfferedForSale[id] = Offer(false, id, offer.seller, 0, 0x0);
pendingWithdrawals[offer.seller] += msg.value;
}
/// @notice Allows an account to enter a higher bid on a toekn
/// @param tokenId the id of the token
function enterBidForGanToken(uint256 tokenId) external payable {
Bid memory existing = tokenBids[tokenId];
require(tokenIdToOwner[tokenId] != msg.sender);
require(tokenIdToOwner[tokenId] != 0x0);
require(msg.value > existing.value);
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
tokenBids[tokenId] = Bid(true, tokenId, msg.sender, msg.value);
emit BidForGanTokenOffered(tokenId, msg.value, msg.sender);
}
/// @notice Allows the owner of a token to accept an outstanding bid for that token
/// @param tokenId The id of the token that's being created
/// @param price The desired price of token in wei
function acceptBid(uint256 tokenId, uint256 price) external payable {
require(tokenIdToOwner[tokenId] == msg.sender);
Bid memory bid = tokenBids[tokenId];
require(bid.value != 0);
require(bid.value == price);
safeTransferFrom(msg.sender, bid.bidder, tokenId);
tokenBids[tokenId] = Bid(false, tokenId, address(0), 0);
pendingWithdrawals[msg.sender] += bid.value;
}
/// @notice Check is a given id is on sale
/// @param tokenId The id of the token in question
/// @return a bool whether of not the token is on sale
function isOnSale(uint256 tokenId) external view returns (bool) {
return ganTokenOfferedForSale[tokenId].isForSale;
}
/// @notice Gets all the sale data related to a token
/// @param tokenId The id of the token
/// @return sale information
function getSaleData(uint256 tokenId) public view returns (bool isForSale, address seller, uint value, address onlySellTo) {
Offer memory offer = ganTokenOfferedForSale[tokenId];
isForSale = offer.isForSale;
seller = offer.seller;
value = offer.value;
onlySellTo = offer.onlySellTo;
}
/// @notice Gets all the bid data related to a token
/// @param tokenId The id of the token
/// @return bid information
function getBidData(uint256 tokenId) view public returns (bool hasBid, address bidder, uint value) {
Bid memory bid = tokenBids[tokenId];
hasBid = bid.hasBid;
bidder = bid.bidder;
value = bid.value;
}
/// @notice Allows a bidder to withdraw their bid
/// @param tokenId The id of the token
function withdrawBid(uint256 tokenId) external payable {
Bid memory bid = tokenBids[tokenId];
require(tokenIdToOwner[tokenId] != msg.sender);
require(tokenIdToOwner[tokenId] != 0x0);
require(bid.bidder == msg.sender);
emit BidWithdrawn(tokenId, bid.value, msg.sender);
uint amount = bid.value;
tokenBids[tokenId] = Bid(false, tokenId, 0x0, 0);
// Refund the bid money
msg.sender.transfer(amount);
}
/// @notice Allows a sender to withdraw any amount in the contrat
function withdraw() external {
uint256 amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
} | Allows an account to enter a higher bid on a toekn tokenId the id of the token Refund the failing bid | function enterBidForGanToken(uint256 tokenId) external payable {
Bid memory existing = tokenBids[tokenId];
require(tokenIdToOwner[tokenId] != msg.sender);
require(tokenIdToOwner[tokenId] != 0x0);
require(msg.value > existing.value);
if (existing.value > 0) {
pendingWithdrawals[existing.bidder] += existing.value;
}
tokenBids[tokenId] = Bid(true, tokenId, msg.sender, msg.value);
emit BidForGanTokenOffered(tokenId, msg.value, msg.sender);
}
| 7,691,945 |
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
//Properties used for Arilines consensus
uint private constant MIN_REGISTERED_AIRLINES_TO_VOTE = 4; //When do we start needing requiring votes?
mapping( address => address[] ) private currentVotes; //Mapping for votes
FlightSuretyDataInterface private dataContract;
uint private constant MAXIMUM_INSURED_AMOUNT = 1 ether;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
/********************************************************************************************/
/* 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()
{
// Modify to call data contract's status
require(true, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
//Ensures the caller is actually a registered airline
modifier requireRegisteredAirline()
{
require( dataContract.isAirline( msg.sender ), "Caller of the contract is not a registered airline!" );
_;
}
modifier requireValidAmount()
{
require( msg.value <= MAXIMUM_INSURED_AMOUNT, "Amount to be insureed to big.");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor
(
address dataAddress
)
public
{
contractOwner = msg.sender;
//Initializes the data contract address
dataContract = FlightSuretyDataInterface( dataAddress );
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
view
returns(bool)
{
//Calls corresponding method in the data contract
return dataContract.isOperational();
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline
(
address airlineAddress
)
public
requireRegisteredAirline
returns(bool, uint)
{
//require( dataContract.isAirline(msg.sender), "Somethign is wrong");
//By default, the total number of votes is 0
uint airlineVotes = 0;
bool success = false;
if (dataContract.getNumberOfRegisteredAirlines() < MIN_REGISTERED_AIRLINES_TO_VOTE) {
//We are in the case where we do not have enough airlines to vote
//So we just need to add its data to the collection and making it awaiting funding
dataContract.registerAirline(airlineAddress, false, true);
success = true;
}
else {
//We need to vote, and this operation is considered as a vote.
//The votes are counted using a list of addresses
//First, we get the list of current votes
address[] storage votes = currentVotes[ airlineAddress ];
bool hasVoted = false;
//We loop through the voting mechanism to ensure this airline has not already voted
for (uint i=0; i<votes.length; i++) {
if (votes[i]==msg.sender) {
hasVoted = true;
break;
}
}
//We fail if the registerer is trying to vote again
require( !hasVoted, "Airline cannot vote twice for the same candidate" );
//Otherwise, we add the current address to list
currentVotes[ airlineAddress ].push( msg.sender );
//The current number of votes is simply the lenght of the votes list
airlineVotes = currentVotes[ airlineAddress ].length;
if (airlineVotes >= requiredVotes()) {
//The airline can now be considered registered as "AWAITING FUNDING"
dataContract.registerAirline(airlineAddress, false, true);
success = true;
}
else {
//The airline sill needs more votes so we simply leave it as it is
dataContract.registerAirline(airlineAddress, false, false);
}
}
return (success, airlineVotes);
}
/*
* Simple function returning the required number of votes
*/
function requiredVotes() public view returns(uint)
{
return SafeMath.div( dataContract.getNumberOfRegisteredAirlines(), 2 );
}
function fundAirline
(
)
public
payable
{
require( msg.value >= 10 ether, "Not enough ether was provided" );
dataContract.fund.value(10 ether )( msg.sender );
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
)
external
pure
{
}
function insureFlight
(
address airline,
string memory flight,
uint256 timestamp
)
public
payable
requireValidAmount
{
//We compute the flight key
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
//We build the key to get a possible already registered amount
bytes32 amountKey = getAmountKey( flightKey, msg.sender );
//We get the amount (will return 0 if non-existent)
uint insuredAmount = dataContract.getInsuredAmount( amountKey );
//We check the value does not exceed
require(insuredAmount + msg.value <= MAXIMUM_INSURED_AMOUNT, "Insured amount is too big");
//We send the amount to the data contract
dataContract.buy.value(msg.value)(msg.sender, amountKey, flightKey);
}
/*
* Allows a speicific user to show how much he has insured a flight for.
*/
function getInsuredAmount(address airline,
string memory flight,
uint256 timestamp)
public view
returns(uint)
{
//We compute the flight key
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
//We build the key to get a possible already registered amount
bytes32 amountKey = getAmountKey( flightKey, msg.sender );
return dataContract.getInsuredAmount( amountKey );
}
/*
* Allows sender to see how much ether he has available
*/
function getBalance()
public view
returns(uint)
{
return dataContract.getBalance(msg.sender);
}
function withdraw()
public
{
//Simply asks the data contract to pay whatever is available.
dataContract.pay(msg.sender);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
{
//We first tell the data contract to update the status of the flight
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
require( dataContract.getFlightStatus(flightKey) == STATUS_CODE_UNKNOWN, "Flight status has already been set!" );
dataContract.updateFlightStatus(flightKey, statusCode);
//We check if the flight was delayed because of the airline
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
//In this case, we retrieve all clients who had bought an insurance for the given flight
address[] memory insurees = dataContract.getFlightInsurees(flightKey);
//Credit their account in the data contract
for (uint i=0; i<insurees.length; i++) {
//We build the key
bytes32 amountKey = getAmountKey( flightKey, insurees[i] );
//We get the amount
uint insuredAmount = dataContract.getInsuredAmount( amountKey );
//Amount to credit is computed by multiplying by 3 and dividing by 2
//which is the integer equivalent of multiplying by 1.5
uint amountToCredit = SafeMath.div( SafeMath.mul(insuredAmount, 3), 2);
//We credit the account of the insuree
dataContract.creditInsurees(insurees[i], amountToCredit);
}
}
}
/*
* Generates hash key for insured amount by combining the flight hash key
* and the insuree address
*/
function getAmountKey
(
bytes32 flightKey,
address insuree
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(flightKey, insuree));
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
public
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle
(
)
public
payable
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes
(
)
view
external
returns(uint8[3])
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
public
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request, or responses is closed");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
//We need to close the request now
oracleResponses[key].isOpen = false;
}
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3])
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
//Contract interface for Data contract
contract FlightSuretyDataInterface {
function isOperational()
public
view
returns(bool);
function registerAirline
(
address airlineAddress,
bool isRegistered,
bool awaitsFunding
)
public;
function getNumberOfRegisteredAirlines() external view returns(uint);
function isAirline
(
address airlineAddress
)
public
view
returns(bool);
function fund
(
address airlineAddress
)
public
payable;
function getFlightStatus( bytes32 flightKey )
external
view
returns(uint8);
function updateFlightStatus
(
bytes32 flightKey,
uint8 statusCode
) external;
function getFlightInsurees( bytes32 flightKey )
external view returns( address[] );
function getInsuredAmount( bytes32 insuredAmountKey )
external view returns( uint );
function creditInsurees
(
address insureeAddress,
uint amount
)
external;
function getBalance( address insureeAddress )
external
view
returns(uint);
function buy
(
address insureeAddress,
bytes32 amountKey,
bytes32 flightKey
)
external
payable;
function pay
(
address insureeAddress
)
external;
} | Allows a speicific user to show how much he has insured a flight for./We compute the flight keyWe build the key to get a possible already registered amount | function getInsuredAmount(address airline,
string memory flight,
uint256 timestamp)
public view
returns(uint)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
bytes32 amountKey = getAmountKey( flightKey, msg.sender );
return dataContract.getInsuredAmount( amountKey );
}
| 13,118,112 |
./full_match/1/0x558055ae71ee1BC926905469301a232066eD4673/sources/contracts/ProtocolGovernance.sol | @inheritdoc IProtocolGovernance | function stagedPermissionGrantsAddresses() external view returns (address[] memory) {
return _stagedPermissionGrantsAddresses.values();
}
| 4,904,543 |
./partial_match/42/0xc85F63DD9B9fC1C2842aD640174eD5421b991ba6/sources/Hour.sol | Transfer `amount` tokens from `msg.sender` to `dst` dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/ | function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Hour::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
| 3,483,823 |
//Address: 0x82c7a0c5e9c8c435df21e00eecea76106054fbf8
//Contract name: KimContract
//Balance: 0.344643620094497854 Ether
//Verification Date: 2/15/2018
//Transacion Count: 299
// CODE STARTS HERE
pragma solidity ^0.4.18;
contract KimAccessControl {
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
}
contract KimContract is KimAccessControl{
// DECLARING BASIC VARIABLES, TOKEN SYMBOLS, AND CONSTANTS
// Public variables of the token
string public name;
string public symbol;
// total supply of kims ever to be in circulation
uint256 public totalSupply;
// Total Kims "released" into the market
uint256 public kimsCreated;
// Total Kims on sale at any given time
uint256 public kimsOnAuction;
// This is the cut each seller will take on the sale of a KIM
uint256 public sellerCut;
// A variable to house mathematic function used in _computeCut function
uint constant feeDivisor = 100;
// Map an owners address to the total amount of KIMS that they own
mapping (address => uint256) public balanceOf;
// Map the KIM to the owner, "Who owns this Kim?"
mapping (uint => address) public tokenToOwner;
// This creates a mapping of the tokenId to an Auction
mapping (uint256 => TokenAuction) public tokenAuction;
// How much ether does this wallet have to withdraw?
mapping (address => uint) public pendingWithdrawals;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event TokenAuctionCreated(uint256 tokenIndex, address seller, uint256 sellPrice);
event TokenAuctionCompleted(uint256 tokenIndex, address seller, address buyer, uint256 sellPrice);
event Withdrawal(address to, uint256 amount);
/* Initializes contract with initial supply tokens to the creator of the contract */
function KimContract() public {
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// Initiate the contract with inital supply of Kims
totalSupply = 5000;
// Give all initial kims to the contract itself
balanceOf[this] = totalSupply; // Give the creator all initial tokens
// This is what we will call KIMs
name = "KimJongCrypto";
symbol = "KJC";
// Declaring seller cut on initalization of the contract
sellerCut = 95;
}
// contstruct the array struct
struct TokenAuction {
bool isForSale;
uint256 tokenIndex;
address seller;
uint256 sellPrice;
uint256 startedAt;
}
// Only the COO can release new KIMS into the market
// We do not have power over the MAXIMUM amount of KIMS that will exist in the future
// That was declared when we created the contract
// KIMJONGCRYPTO.COM will release KIMS periodically to maintain a healthy market flow
function releaseSomeKims(uint256 howMany) external onlyCOO {
// We promise not to manipulate the markets, so we take an
// average of all the KIMS on sale at any given time
uint256 marketAverage = averageKimSalePrice();
for(uint256 counter = 0; counter < howMany; counter++) {
// map the token to the tokenOwner
tokenToOwner[counter] = this;
// Put the KIM out on the market for sale
_tokenAuction(kimsCreated, this, marketAverage);
// Record the amount of KIMS released
kimsCreated++;
}
}
// Don't want to keep this KIM?
// Sell KIM then...
function sellToken(uint256 tokenIndex, uint256 sellPrice) public {
// Which KIM are you selling?
TokenAuction storage tokenOnAuction = tokenAuction[tokenIndex];
// Who's selling the KIM, stored into seller variable
address seller = msg.sender;
// Do you own this kim?
require(_owns(seller, tokenIndex));
// Is the KIM already on sale? Can't sell twice!
require(tokenOnAuction.isForSale == false);
// CLEAR! Send that KIM to Auction!
_tokenAuction(tokenIndex, seller, sellPrice);
}
// INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT
function _tokenAuction(uint256 tokenIndex, address seller, uint256 sellPrice) internal {
// Set the Auction Struct to ON SALE
tokenAuction[tokenIndex] = TokenAuction(true, tokenIndex, seller, sellPrice, now);
// Fire the Auction Created Event, tell the whole wide world!
TokenAuctionCreated(tokenIndex, seller, sellPrice);
// Increase the amount of KIMS being sold!
kimsOnAuction++;
}
// Like a KIM?
// BUY IT!
function buyKim(uint256 tokenIndex) public payable {
// Store the KIM in question into tokenOnAuction variable
TokenAuction storage tokenOnAuction = tokenAuction[tokenIndex];
// How much is this KIM on sale for?
uint256 sellPrice = tokenOnAuction.sellPrice;
// Is the KIM even on sale? No monkey business!
require(tokenOnAuction.isForSale == true);
// You are going to have to pay for this KIM! make sure you send enough ether!
require(msg.value >= sellPrice);
// Who's selling their KIM?
address seller = tokenOnAuction.seller;
// Who's trying to buy this KIM?
address buyer = msg.sender;
// CLEAR!
// Complete the auction! And transfer the KIM!
_completeAuction(tokenIndex, seller, buyer, sellPrice);
}
// INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT
function _completeAuction(uint256 tokenIndex, address seller, address buyer, uint256 sellPrice) internal {
// Store the contract address
address thisContract = this;
// How much commision will the Auction House take?
uint256 auctioneerCut = _computeCut(sellPrice);
// How much will the seller take home?
uint256 sellerProceeds = sellPrice - auctioneerCut;
// If the KIM is being sold by the Auction House, then do this...
if (seller == thisContract) {
// Give the funds to the House
pendingWithdrawals[seller] += sellerProceeds + auctioneerCut;
// Close the Auction
tokenAuction[tokenIndex] = TokenAuction(false, tokenIndex, 0, 0, 0);
// Anounce it to the world!
TokenAuctionCompleted(tokenIndex, seller, buyer, sellPrice);
} else { // If the KIM is being sold by an Individual, then do this...
// Give the funds to the seller
pendingWithdrawals[seller] += sellerProceeds;
// Give the funds to the House
pendingWithdrawals[this] += auctioneerCut;
// Close the Auction
tokenAuction[tokenIndex] = TokenAuction(false, tokenIndex, 0, 0, 0);
// Anounce it to the world!
TokenAuctionCompleted(tokenIndex, seller, buyer, sellPrice);
}
_transfer(seller, buyer, tokenIndex);
kimsOnAuction--;
}
// Don't want to sell KIM anymore?
// Cancel Auction
function cancelKimAuction(uint kimIndex) public {
require(_owns(msg.sender, kimIndex));
// Store the KIM in question into tokenOnAuction variable
TokenAuction storage tokenOnAuction = tokenAuction[kimIndex];
// Is the KIM even on sale? No monkey business!
require(tokenOnAuction.isForSale == true);
// Close the Auction
tokenAuction[kimIndex] = TokenAuction(false, kimIndex, 0, 0, 0);
}
// INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT
// Use this function to find out how much the AuctionHouse will take from this Transaction
// All funds go to KIMJONGCRYPTO BCD(BLOCKCHAIN DEVS)!
function _computeCut(uint256 sellPrice) internal view returns (uint) {
return sellPrice * sellerCut / 1000;
}
// INTERNAL FUNCTION, USED ONLY FROM WITHIN THE CONTRACT
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Subtract from the sender
balanceOf[_from]--;
// Add to the reciever
balanceOf[_to]++;
// map the token to the tokenOwner
tokenToOwner[_value] = _to;
Transfer(_from, _to, 1);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
// Go ahead and give away a KIM as a gift!
function transfer(address _to, uint256 _value) public {
require(_owns(msg.sender, _value));
_transfer(msg.sender, _to, _value);
}
// this function returns bool of owenrship over the token.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return tokenToOwner[_tokenId] == _claimant;
}
// How much are KIMS really going for now a days?
// Run this function and find out!
function averageKimSalePrice() public view returns (uint256) {
uint256 sumOfAllKimAuctions = 0;
if (kimsOnAuction == 0){
return 0;
} else {
for (uint256 i = 0; i <= kimsOnAuction; i++) {
sumOfAllKimAuctions += tokenAuction[i].sellPrice;
}
return sumOfAllKimAuctions / kimsOnAuction;
}
}
// this function serves for users to withdraw their ethereum
function withdraw() {
uint amount = pendingWithdrawals[msg.sender];
require(amount > 0);
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
Withdrawal(msg.sender, amount);
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint balance = pendingWithdrawals[this];
pendingWithdrawals[this] = 0;
cfoAddress.transfer(balance);
Withdrawal(cfoAddress, balance);
}
}
| Assigns a new address to act as the CFO. Only available to the current CEO. _newCFO The address of the new CFO | function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
| 12,761,673 |
pragma solidity 0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface Token {
function transfer(address _to, uint256 _amount)external returns (bool success);
function balanceOf(address _owner) external returns (uint256 balance);
function decimals()external view returns (uint8);
}
/**
* @title Vault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Funds will be transferred to owner on adhoc requests
*/
contract Vault is Ownable {
using SafeMath for uint256;
mapping (address => uint256) public deposited;
address public wallet;
event Withdrawn(address _wallet);
function Vault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
function deposit(address investor) public onlyOwner payable{
deposited[investor] = deposited[investor].add(msg.value);
}
function withdrawToWallet() public onlyOwner {
wallet.transfer(this.balance);
emit Withdrawn(wallet);
}
}
contract CLXTokenSale is Ownable{
using SafeMath for uint256;
//Token to be used for this sale
Token public token;
//All funds will go into this vault
Vault public vault;
//rate of token in ether 1ETH = 8000 CLX
uint256 public rate = 8000;
/*
*There will be 2 phases
* 1. Pre-sale
* 2. ICO Phase 1
*/
struct PhaseInfo{
uint256 hardcap;
uint256 startTime;
uint256 endTime;
uint8 bonusPercentages;
uint256 minEtherContribution;
uint256 weiRaised;
}
//info of each phase
PhaseInfo[] public phases;
//Total funding
uint256 public totalFunding;
//total tokens available for sale considering 8 decimal places
uint256 tokensAvailableForSale = 17700000000000000;
uint8 public noOfPhases;
//Keep track of whether contract is up or not
bool public contractUp;
//Keep track of whether the sale has ended or not
bool public saleEnded;
//Keep track of emergency stop
bool public ifEmergencyStop ;
//Event to trigger Sale stop
event SaleStopped(address _owner, uint256 time);
//Event to trigger Sale restart
event SaleRestarted(address _owner, uint256 time);
//Event to trigger normal flow of sale end
event Finished(address _owner, uint256 time);
/**
* 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);
//modifiers
modifier _contractUp(){
require(contractUp);
_;
}
modifier nonZeroAddress(address _to) {
require(_to != address(0));
_;
}
modifier _saleEnded() {
require(saleEnded);
_;
}
modifier _saleNotEnded() {
require(!saleEnded);
_;
}
modifier _ifNotEmergencyStop() {
require(!ifEmergencyStop);
_;
}
/**
* @dev Check if sale contract has enough tokens on its account balance
* to reward all possible participations within sale period
*/
function powerUpContract() external onlyOwner {
// Contract should not be powered up previously
require(!contractUp);
// Contract should have enough CLX credits
require(token.balanceOf(this) >= tokensAvailableForSale);
//activate the sale process
contractUp = true;
}
//for Emergency stop of the sale
function emergencyStop() external onlyOwner _contractUp _ifNotEmergencyStop {
ifEmergencyStop = true;
emit SaleStopped(msg.sender, now);
}
//to restart the sale after emergency stop
function emergencyRestart() external onlyOwner _contractUp {
require(ifEmergencyStop);
ifEmergencyStop = false;
emit SaleRestarted(msg.sender, now);
}
// @return true if all the tiers has been ended
function saleTimeOver() public view returns (bool) {
return (phases[noOfPhases-1].endTime != 0);
}
/**
* @dev Can be called only once. The method to allow owner to set tier information
* @param _noOfPhases The integer to set number of tiers
* @param _startTimes The array containing start time of each tier
* @param _endTimes The array containing end time of each tier
* @param _hardCaps The array containing hard cap for each tier
* @param _bonusPercentages The array containing bonus percentage for each tier
* The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3 and 4 .
* Sales hard cap will be the hard cap of last tier
*/
function setTiersInfo(uint8 _noOfPhases, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps ,uint256[] _minEtherContribution, uint8[2] _bonusPercentages)private {
require(_noOfPhases == 2);
//Each array should contain info about each tier
require(_startTimes.length == 2);
require(_endTimes.length == _noOfPhases);
require(_hardCaps.length == _noOfPhases);
require(_bonusPercentages.length == _noOfPhases);
noOfPhases = _noOfPhases;
for(uint8 i = 0; i < _noOfPhases; i++){
require(_hardCaps[i] > 0);
if(i>0){
phases.push(PhaseInfo({
hardcap:_hardCaps[i],
startTime:_startTimes[i],
endTime:_endTimes[i],
minEtherContribution : _minEtherContribution[i],
bonusPercentages:_bonusPercentages[i],
weiRaised:0
}));
}
else{
//start time of tier1 should be greater than current time
require(_startTimes[i] > now);
phases.push(PhaseInfo({
hardcap:_hardCaps[i],
startTime:_startTimes[i],
minEtherContribution : _minEtherContribution[i],
endTime:_endTimes[i],
bonusPercentages:_bonusPercentages[i],
weiRaised:0
}));
}
}
}
/**
* @dev Constructor method
* @param _tokenToBeUsed Address of the token to be used for Sales
* @param _wallet Address of the wallet which will receive the collected funds
*/
function CLXTokenSale(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){
token = Token(_tokenToBeUsed);
vault = new Vault(_wallet);
uint256[] memory startTimes = new uint256[](2);
uint256[] memory endTimes = new uint256[](2);
uint256[] memory hardCaps = new uint256[](2);
uint256[] memory minEtherContribution = new uint256[](2);
uint8[2] memory bonusPercentages;
//pre-sales
startTimes[0] = 1525910400; //MAY 10, 2018 00:00 AM GMT
endTimes[0] = 0; //NO END TIME INITIALLY
hardCaps[0] = 7500 ether;
minEtherContribution[0] = 0.3 ether;
bonusPercentages[0] = 20;
//phase-1: Public Sale
startTimes[1] = 0; //NO START TIME INITIALLY
endTimes[1] = 0; //NO END TIME INITIALLY
hardCaps[1] = 12500 ether;
minEtherContribution[1] = 0.1 ether;
bonusPercentages[1] = 5;
setTiersInfo(2, startTimes, endTimes, hardCaps, minEtherContribution, bonusPercentages);
}
//Fallback function used to buytokens
function()public payable{
buyTokens(msg.sender);
}
function startNextPhase() public onlyOwner _saleNotEnded _contractUp _ifNotEmergencyStop returns(bool){
int8 currentPhaseIndex = getCurrentlyRunningPhase();
require(currentPhaseIndex == 0);
PhaseInfo storage currentlyRunningPhase = phases[uint256(currentPhaseIndex)];
uint256 tokensLeft;
uint256 tokensInPreICO = 7200000000000000; //considering 8 decimal places
//Checking if tokens are left after the Pre ICO sale, if left, transfer all to the owner
if(currentlyRunningPhase.weiRaised <= 7500 ether) {
tokensLeft = tokensInPreICO.sub(currentlyRunningPhase.weiRaised.mul(9600).div(10000000000));
token.transfer(msg.sender, tokensLeft);
}
phases[0].endTime = now;
phases[1].startTime = now;
return true;
}
/**
* @dev Must be called to end the sale, to do some extra finalization
* work. It finishes the sale, sends the unsold tokens to the owner's address
* IMP : Call withdrawFunds() before finishing the sale
*/
function finishSale() public onlyOwner _contractUp _saleNotEnded returns (bool){
int8 currentPhaseIndex = getCurrentlyRunningPhase();
require(currentPhaseIndex == 1);
PhaseInfo storage currentlyRunningPhase = phases[uint256(currentPhaseIndex)];
uint256 tokensLeft;
uint256 tokensInPublicSale = 10500000000000000; //considering 8 decimal places
//Checking if tokens are left after the Public sale, if left, transfer all to the owner
if(currentlyRunningPhase.weiRaised <= 12500 ether) {
tokensLeft = tokensInPublicSale.sub(currentlyRunningPhase.weiRaised.mul(8400).div(10000000000));
token.transfer(msg.sender, tokensLeft);
}
//End the sale
saleEnded = true;
//Set the endTime of Public Sale
phases[noOfPhases-1].endTime = now;
emit Finished(msg.sender, now);
return true;
}
/**
* @dev Low level token purchase function
* @param beneficiary The address who will receive the tokens for this transaction
*/
function buyTokens(address beneficiary)public _contractUp _saleNotEnded _ifNotEmergencyStop nonZeroAddress(beneficiary) payable returns(bool){
int8 currentPhaseIndex = getCurrentlyRunningPhase();
assert(currentPhaseIndex >= 0);
// recheck this for storage and memory
PhaseInfo storage currentlyRunningPhase = phases[uint256(currentPhaseIndex)];
uint256 weiAmount = msg.value;
//Check hard cap for this phase has not been reached
require(weiAmount.add(currentlyRunningPhase.weiRaised) <= currentlyRunningPhase.hardcap);
//check the minimum ether contribution
require(weiAmount >= currentlyRunningPhase.minEtherContribution);
uint256 tokens = weiAmount.mul(rate).div(10000000000);//considering decimal places to be 8 for token
uint256 bonusedTokens = applyBonus(tokens, currentlyRunningPhase.bonusPercentages);
totalFunding = totalFunding.add(weiAmount);
currentlyRunningPhase.weiRaised = currentlyRunningPhase.weiRaised.add(weiAmount);
vault.deposit.value(msg.value)(msg.sender);
token.transfer(beneficiary, bonusedTokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens);
return true;
}
/**
*@dev Method to calculate bonus for the user as per currently running phase and contribution by the user
* @param tokens Total tokens purchased by the user
* @param percentage Array of bonus percentages for the phase
*/
function applyBonus(uint256 tokens, uint8 percentage) private pure returns (uint256) {
uint256 tokensToAdd = 0;
tokensToAdd = tokens.mul(percentage).div(100);
return tokens.add(tokensToAdd);
}
/**
* @dev returns the currently running tier index as per time
* Return -1 if no tier is running currently
* */
function getCurrentlyRunningPhase()public view returns(int8){
for(uint8 i=0;i<noOfPhases;i++){
if(phases[i].startTime!=0 && now>=phases[i].startTime && phases[i].endTime == 0){
return int8(i);
}
}
return -1;
}
/**
* @dev Get funding info of user/address.
* It will return how much funding the user has made in terms of wei
*/
function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){
return vault.deposited(_user);
}
/**
* @dev Allow owner to withdraw funds to his wallet anytime in between the sale process
*/
function withDrawFunds()public onlyOwner _saleNotEnded _contractUp {
vault.withdrawToWallet();
}
} | Method to calculate bonus for the user as per currently running phase and contribution by the user tokens Total tokens purchased by the user percentage Array of bonus percentages for the phase/ | function applyBonus(uint256 tokens, uint8 percentage) private pure returns (uint256) {
uint256 tokensToAdd = 0;
tokensToAdd = tokens.mul(percentage).div(100);
return tokens.add(tokensToAdd);
}
| 411,170 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "./ExampleExternalContract.sol"; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
contract Staker {
ExampleExternalContract public exampleExternalContract;
constructor(address exampleExternalContractAddress) {
exampleExternalContract = ExampleExternalContract(exampleExternalContractAddress);
}
mapping (address => uint256) public balances;
uint256 public threshold = 1 ether;
uint256 public deadline = block.timestamp + 24 hours;
event Withdraw(address indexed withdrawer, uint256 amount);
event Stake(address indexed staker, uint256 balance);
bool public openForWithdraw = false;
modifier deadlineReached(bool beforeDeadline) {
if(beforeDeadline) {
require(block.timestamp < deadline, "Deadline is already reached");
} else {
require(block.timestamp >= deadline, "Deadline not yet reached");
}
_;
}
modifier notCompleted() {
require(
exampleExternalContract.completed() == false,
"ExampleExternalContract is not complete"
);
_;
}
// Collect funds in a payable `stake()` function and track individual `balances` with a mapping:
// ( make sure to add a `Stake(address,uint256)` event and emit it for the frontend <List/> display )
function stake() public payable deadlineReached(true) notCompleted {
balances[msg.sender] += msg.value;
emit Stake(msg.sender, msg.value);
}
// After some `deadline` allow anyone to call an `execute()` function
// It should either call `exampleExternalContract.complete{value: address(this).balance}()` to send all the value
function execute() public payable deadlineReached(false) notCompleted {
uint256 contractBalance = address(this).balance;
// check the contract has enough ETH to reach the treshold
require(contractBalance >= threshold, "Threshold not reached");
// Execute the external contract, transfer all the balance to the contract
// (bool sent, bytes memory data) = exampleExternalContract.complete{value: contractBalance}();
(bool sent,) = address(exampleExternalContract).call{value: contractBalance}(abi.encodeWithSignature("complete()"));
require(sent, "exampleExternalContract.complete failed");
}
// if the `threshold` was not met, allow everyone to call a `withdraw()` function
function withdraw() public payable notCompleted {
uint256 contractBalance = address(this).balance;
if (block.timestamp >= deadline && contractBalance > threshold) {
revert("Threshold met deadline and stake amount cannot be withdrawn.");
}
uint256 userBalance = balances[msg.sender];
require(userBalance > 0, "Empty Balance");
balances[msg.sender] = 0;
// Transfer balance back to the user
(bool sent,) = msg.sender.call{value: userBalance}("");
require(sent, "Failed to send user balance back to the user");
}
// Add a `timeLeft()` view function that returns the time left before the deadline for the frontend
function timeLeft() public view returns (uint256) {
if( block.timestamp >= deadline ) {
return 0;
}
return deadline - block.timestamp;
}
}
| Collect funds in a payable `stake()` function and track individual `balances` with a mapping: ( make sure to add a `Stake(address,uint256)` event and emit it for the frontend <List/> display ) | function stake() public payable deadlineReached(true) notCompleted {
balances[msg.sender] += msg.value;
emit Stake(msg.sender, msg.value);
}
| 12,902,365 |
./partial_match/1/0x653348F7Dc5117E3c9D469ba55136716F28dBb11/sources/GROOVY.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("GROOVY", "GRVY") {
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 = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
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);
| 16,050,300 |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IHabitat.sol";
import "./interfaces/IHouseTraits.sol";
import "./interfaces/ICHEDDAR.sol";
import "./interfaces/IHouse.sol";
import "./interfaces/IRandomizer.sol";
contract HouseGame is Ownable, ReentrancyGuard, Pausable {
event MintCommitted(address indexed owner, uint256 indexed amount);
event MintRevealed(address indexed owner, uint256 indexed amount);
struct MintCommit {
bool stake;
uint16 amount;
}
// address -> commit id -> commits
mapping(address => mapping(uint16 => MintCommit)) private _mintCommits;
// address -> commit num of commit need revealed for account
mapping(address => uint16) private _pendingCommitId;
// pending mint amount
uint16 private pendingMintAmt;
// flag for commits allowment
bool public allowCommits = true;
// address => can call addCommitRandom
mapping(address => bool) private admins;
// reference to the Habitat for choosing random Cat thieves
IHabitat public habitat;
// reference to $CHEDDAR for burning on mint
ICHEDDAR public cheddarToken;
// reference to House Traits
IHouseTraits public houseTraits;
// reference to House NFT collection
IHouse public houseNFT;
// reference to IRandomizer
IRandomizer public randomizer;
constructor() {
_pause();
}
/** CRITICAL TO SETUP */
modifier requireContractsSet() {
require(address(cheddarToken) != address(0) && address(houseTraits) != address(0)
&& address(habitat) != address(0) && address(houseNFT) != address(0) && address(randomizer) != address(0)
, "Contracts not set");
_;
}
function setContracts(address _cheddar,address _houseTraits, address _habitat, address _house, address _randomizer) external onlyOwner {
cheddarToken = ICHEDDAR(_cheddar);
habitat = IHabitat(_habitat);
houseNFT = IHouse(_house);
houseTraits = IHouseTraits(_houseTraits);
randomizer = IRandomizer(_randomizer);
}
/** EXTERNAL */
function getPendingMint(address addr) external view returns (MintCommit memory) {
require(_pendingCommitId[addr] != 0, "no pending commits");
return _mintCommits[addr][_pendingCommitId[addr]];
}
function hasMintPending(address addr) external view returns (bool) {
return _pendingCommitId[addr] != 0;
}
function canMint(address addr) external view returns (bool) {
return _pendingCommitId[addr] != 0 && randomizer.getCommitRandom(_pendingCommitId[addr]) > 0;
}
function deleteCommit(address addr) external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
uint16 commitIdCur = _pendingCommitId[_msgSender()];
require(commitIdCur > 0, "No pending commit");
delete _mintCommits[addr][commitIdCur];
delete _pendingCommitId[addr];
}
function forceRevealCommit(address addr) external {
require(owner() == _msgSender() || admins[_msgSender()], "Only admins can call this");
reveal(addr);
}
/** Initiate the start of a mint. This action burns $CHEDDAR, as the intent of committing is that you cannot back out once you've started.
* This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this
* commit was added to. */
function mintCommit(uint256 amount, bool stake) external whenNotPaused nonReentrant {
require(allowCommits, "adding commits disallowed");
require(tx.origin == _msgSender(), "Only EOA");
require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints");
uint16 minted = houseNFT.minted();
uint256 maxTokens = houseNFT.getMaxTokens();
require(minted + pendingMintAmt + amount <= maxTokens, "All tokens minted");
require(amount > 0 && amount <= 10, "Invalid mint amount");
uint256 totalCheddarCost = 0;
// Loop through the amount of
for (uint i = 1; i <= amount; i++) {
totalCheddarCost += mintCost(minted + pendingMintAmt + i, maxTokens);
}
if (totalCheddarCost > 0) {
cheddarToken.burn(_msgSender(), totalCheddarCost);
cheddarToken.updateOriginAccess();
}
uint16 amt = uint16(amount);
_mintCommits[_msgSender()][randomizer.commitId()] = MintCommit(stake, amt);
_pendingCommitId[_msgSender()] = randomizer.commitId();
pendingMintAmt += amt;
emit MintCommitted(_msgSender(), amount);
}
/** Reveal the commits for this user. This will be when the user gets their NFT, and can only be done when the commit id that
* the user is pending for has been assigned a random seed. */
function mintReveal() external whenNotPaused nonReentrant {
require(tx.origin == _msgSender(), "Only EOA1");
reveal(_msgSender());
}
function reveal(address addr) internal {
uint16 commitIdCur = _pendingCommitId[addr];
uint256 seed = randomizer.getCommitRandom(commitIdCur);
require(commitIdCur > 0, "No pending commit");
require(seed > 0, "random seed not set");
uint16 minted = houseNFT.minted();
MintCommit memory commit = _mintCommits[addr][commitIdCur];
pendingMintAmt -= commit.amount;
uint16[] memory tokenIds = new uint16[](commit.amount);
uint16[] memory tokenIdsToStake = new uint16[](commit.amount);
for (uint k = 0; k < commit.amount; k++) {
minted++;
// scramble the random so the steal / treasure mechanic are different per mint
seed = uint256(keccak256(abi.encode(seed, addr)));
address recipient = selectRecipient(seed);
tokenIds[k] = minted;
if (!commit.stake || recipient != addr) {
houseNFT.mint(recipient, seed);
} else {
houseNFT.mint(address(habitat), seed);
tokenIdsToStake[k] = minted;
}
}
houseNFT.updateOriginAccess(tokenIds);
if(commit.stake) {
habitat.addManyHouseToStakingPool(addr, tokenIdsToStake);
}
delete _mintCommits[addr][commitIdCur];
delete _pendingCommitId[addr];
emit MintRevealed(addr, tokenIds.length);
}
/**
* the first 25% are 80000 $CHEDDAR
* the next 50% are 160000 $CHEDDAR
* the next 25% are 320000 $WOOL
* @param tokenId the ID to check the cost of to mint
* @return the cost of the given token ID
*/
function mintCost(uint256 tokenId, uint256 maxTokens) public pure returns (uint256) {
if (tokenId <= maxTokens / 4) return 80000 ether;
if (tokenId <= maxTokens * 3 / 4) return 160000 ether;
return 320000 ether;
}
/** INTERNAL */
/**
* @param seed a random value to select a recipient from
* @return the address of the recipient (either the minter or the Cat thief's owner)
*/
function selectRecipient(uint256 seed) internal view returns (address) {
if (((seed >> 245) % 8) != 0) return _msgSender(); // top 8 bits haven't been used
address thief = habitat.randomCrazyCatOwner(seed >> 144); // 144 bits reserved for trait selection
if (thief == address(0x0)) return _msgSender();
return thief;
}
/** ADMIN */
/**
* enables owner to pause / unpause contract
*/
function setPaused(bool _paused) external requireContractsSet onlyOwner {
if (_paused) _pause();
else _unpause();
}
function setAllowCommits(bool allowed) external onlyOwner {
allowCommits = allowed;
}
/** Allow the contract owner to set the pending mint amount.
* This allows any long-standing pending commits to be overwritten, say for instance if the max supply has been
* reached but there are many stale pending commits, it could be used to free up those spaces if needed/desired by the community.
* This function should not be called lightly, this will have negative consequences on the game. */
function setPendingMintAmt(uint256 pendingAmt) external onlyOwner {
pendingMintAmt = uint16(pendingAmt);
}
/**
* enables an address to mint / burn
* @param addr the address to enable
*/
function addAdmin(address addr) external onlyOwner {
admins[addr] = true;
}
/**
* disables an address from minting / burning
* @param addr the address to disbale
*/
function removeAdmin(address addr) external onlyOwner {
admins[addr] = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IHabitat {
function addManyToStakingPool(address account, uint16[] calldata tokenIds) external;
function addManyHouseToStakingPool(address account, uint16[] calldata tokenIds) external;
function randomCatOwner(uint256 seed) external view returns (address);
function randomCrazyCatOwner(uint256 seed) external view returns (address);
function isOwner(uint256 tokenId, address owner) external view returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IHouseTraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ICHEDDAR {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function updateOriginAccess() external;
function transferFrom(address sender, address recipient, uint256 amount) external returns(bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IHouse is IERC721Enumerable {
// House NFT struct
struct HouseStruct {
uint8 roll; //0 - Shack, 1 - Ranch, 2 - Mansion
uint8 body;
}
function getTokenWriteBlock(uint256 tokenId) external view returns(uint64);
function mint(address recipient, uint256 seed) external;
function burn(uint256 tokenId) external;
function updateOriginAccess(uint16[] memory tokenIds) external;
function isShack(uint256 tokenId) external view returns(bool);
function isRanch(uint256 tokenId) external view returns(bool);
function isMansion(uint256 tokenId) external view returns(bool);
function getMaxTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (HouseStruct memory);
function minted() external view returns (uint16);
function emitShackStakedEvent(address owner, uint256 tokenId) external;
function emitRanchStakedEvent(address owner, uint256 tokenId) external;
function emitMansionStakedEvent(address owner, uint256 tokenId) external;
function emitShackUnStakedEvent(address owner, uint256 tokenId) external;
function emitRanchUnStakedEvent(address owner, uint256 tokenId) external;
function emitMansionUnStakedEvent(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IRandomizer {
function commitId() external view returns (uint16);
function getCommitRandom(uint16 id) external view returns (uint256);
function random() external returns (uint256);
function sRandom(uint256 tokenId) external returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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);
}
| the first 25% are 80000 $CHEDDAR the next 50% are 160000 $CHEDDAR the next 25% are 320000 $WOOL tokenId the ID to check the cost of to mint return the cost of the given token ID/ | function mintCost(uint256 tokenId, uint256 maxTokens) public pure returns (uint256) {
if (tokenId <= maxTokens / 4) return 80000 ether;
if (tokenId <= maxTokens * 3 / 4) return 160000 ether;
return 320000 ether;
}
| 12,755,958 |
./full_match/80001/0xE4fcb71B67B63Fd2f500cfeb01b5bE661be9a334/sources/_thirdweb-dev/contracts/base/Staking1155Base.sol | Admin deposits reward tokens. | function depositRewardTokens(uint256 _amount) external payable virtual nonReentrant {
}
| 842,073 |
./full_match/1/0x2CF4abb70f2732B522DC59cb644b560eE2BF43e6/sources/foraging-contracts/Nom.sol | ERC20 FUNCTIONALITY OVERRIDES_balances is actual supply, balances is hypothetical | function balanceOf(address account) public view override (ERC20) returns (uint256) {
return ERC20.balanceOf(account) + balances[account];
}
| 3,029,807 |
./full_match/1/0xFB75f5e29231a27dD15f560234D8f7C2A3A0E6c8/sources/erc1155delta/contracts/ERC1155DeltaUpgradeable.sol | Transfers `amount` tokens of token type `id` from `from` to `to`. Emits a {TransferSingle} event. Requirements: - `to` cannot be the zero address. - `amount` cannot be zero. - `from` must have a balance of tokens of type `id` of at least `amount`. - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value./ | function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
if(to == address(0)) {
revert TransferToZeroAddress();
}
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
_beforeTokenTransfer(operator, from, to, ids);
if(amount == 1 && ERC1155DeltaStorage.layout()._owned[from].get(id)) {
ERC1155DeltaStorage.layout()._owned[from].unset(id);
ERC1155DeltaStorage.layout()._owned[to].set(id);
revert TransferFromIncorrectOwnerOrInvalidAmount();
}
emit TransferSingle(operator, from, to, id, amount);
_afterTokenTransfer(operator, from, to, ids);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
| 3,083,408 |
pragma solidity ^0.4.24;
contract CrabData {
modifier crabDataLength(uint256[] memory _crabData) {
require(_crabData.length == 8);
_;
}
struct CrabPartData {
uint256 hp;
uint256 dps;
uint256 blockRate;
uint256 resistanceBonus;
uint256 hpBonus;
uint256 dpsBonus;
uint256 blockBonus;
uint256 mutiplierBonus;
}
function arrayToCrabPartData(
uint256[] _partData
)
internal
pure
crabDataLength(_partData)
returns (CrabPartData memory _parsedData)
{
_parsedData = CrabPartData(
_partData[0], // hp
_partData[1], // dps
_partData[2], // block rate
_partData[3], // resistance bonus
_partData[4], // hp bonus
_partData[5], // dps bonus
_partData[6], // block bonus
_partData[7]); // multiplier bonus
}
function crabPartDataToArray(CrabPartData _crabPartData) internal pure returns (uint256[] memory _resultData) {
_resultData = new uint256[](8);
_resultData[0] = _crabPartData.hp;
_resultData[1] = _crabPartData.dps;
_resultData[2] = _crabPartData.blockRate;
_resultData[3] = _crabPartData.resistanceBonus;
_resultData[4] = _crabPartData.hpBonus;
_resultData[5] = _crabPartData.dpsBonus;
_resultData[6] = _crabPartData.blockBonus;
_resultData[7] = _crabPartData.mutiplierBonus;
}
}
contract GeneSurgeon {
//0 - filler, 1 - body, 2 - leg, 3 - left claw, 4 - right claw
uint256[] internal crabPartMultiplier = [0, 10**9, 10**6, 10**3, 1];
function extractElementsFromGene(uint256 _gene) internal view returns (uint256[] memory _elements) {
_elements = new uint256[](4);
_elements[0] = _gene / crabPartMultiplier[1] / 100 % 10;
_elements[1] = _gene / crabPartMultiplier[2] / 100 % 10;
_elements[2] = _gene / crabPartMultiplier[3] / 100 % 10;
_elements[3] = _gene / crabPartMultiplier[4] / 100 % 10;
}
function extractPartsFromGene(uint256 _gene) internal view returns (uint256[] memory _parts) {
_parts = new uint256[](4);
_parts[0] = _gene / crabPartMultiplier[1] % 100;
_parts[1] = _gene / crabPartMultiplier[2] % 100;
_parts[2] = _gene / crabPartMultiplier[3] % 100;
_parts[3] = _gene / crabPartMultiplier[4] % 100;
}
}
interface GenesisCrabInterface {
function generateCrabGene(bool isPresale, bool hasLegendaryPart) external returns (uint256 _gene, uint256 _skin, uint256 _heartValue, uint256 _growthValue);
function mutateCrabPart(uint256 _part, uint256 _existingPartGene, uint256 _legendaryPercentage) external returns (uint256);
function generateCrabHeart() external view returns (uint256, uint256);
}
contract LevelCalculator {
event LevelUp(address indexed tokenOwner, uint256 indexed tokenId, uint256 currentLevel, uint256 currentExp);
event ExpGained(address indexed tokenOwner, uint256 indexed tokenId, uint256 currentLevel, uint256 currentExp);
function expRequiredToReachLevel(uint256 _level) internal pure returns (uint256 _exp) {
require(_level > 1);
uint256 _expRequirement = 10;
for(uint256 i = 2 ; i < _level ; i++) {
_expRequirement += 12;
}
_exp = _expRequirement;
}
}
contract Randomable {
// Generates a random number base on last block hash
function _generateRandom(bytes32 seed) view internal returns (bytes32) {
return keccak256(abi.encodePacked(blockhash(block.number-1), seed));
}
function _generateRandomNumber(bytes32 seed, uint256 max) view internal returns (uint256) {
return uint256(_generateRandom(seed)) % max;
}
}
contract CryptantCrabStoreInterface {
function createAddress(bytes32 key, address value) external returns (bool);
function createAddresses(bytes32[] keys, address[] values) external returns (bool);
function updateAddress(bytes32 key, address value) external returns (bool);
function updateAddresses(bytes32[] keys, address[] values) external returns (bool);
function removeAddress(bytes32 key) external returns (bool);
function removeAddresses(bytes32[] keys) external returns (bool);
function readAddress(bytes32 key) external view returns (address);
function readAddresses(bytes32[] keys) external view returns (address[]);
// Bool related functions
function createBool(bytes32 key, bool value) external returns (bool);
function createBools(bytes32[] keys, bool[] values) external returns (bool);
function updateBool(bytes32 key, bool value) external returns (bool);
function updateBools(bytes32[] keys, bool[] values) external returns (bool);
function removeBool(bytes32 key) external returns (bool);
function removeBools(bytes32[] keys) external returns (bool);
function readBool(bytes32 key) external view returns (bool);
function readBools(bytes32[] keys) external view returns (bool[]);
// Bytes32 related functions
function createBytes32(bytes32 key, bytes32 value) external returns (bool);
function createBytes32s(bytes32[] keys, bytes32[] values) external returns (bool);
function updateBytes32(bytes32 key, bytes32 value) external returns (bool);
function updateBytes32s(bytes32[] keys, bytes32[] values) external returns (bool);
function removeBytes32(bytes32 key) external returns (bool);
function removeBytes32s(bytes32[] keys) external returns (bool);
function readBytes32(bytes32 key) external view returns (bytes32);
function readBytes32s(bytes32[] keys) external view returns (bytes32[]);
// uint256 related functions
function createUint256(bytes32 key, uint256 value) external returns (bool);
function createUint256s(bytes32[] keys, uint256[] values) external returns (bool);
function updateUint256(bytes32 key, uint256 value) external returns (bool);
function updateUint256s(bytes32[] keys, uint256[] values) external returns (bool);
function removeUint256(bytes32 key) external returns (bool);
function removeUint256s(bytes32[] keys) external returns (bool);
function readUint256(bytes32 key) external view returns (uint256);
function readUint256s(bytes32[] keys) external view returns (uint256[]);
// int256 related functions
function createInt256(bytes32 key, int256 value) external returns (bool);
function createInt256s(bytes32[] keys, int256[] values) external returns (bool);
function updateInt256(bytes32 key, int256 value) external returns (bool);
function updateInt256s(bytes32[] keys, int256[] values) external returns (bool);
function removeInt256(bytes32 key) external returns (bool);
function removeInt256s(bytes32[] keys) external returns (bool);
function readInt256(bytes32 key) external view returns (int256);
function readInt256s(bytes32[] keys) external view returns (int256[]);
// internal functions
function parseKey(bytes32 key) internal pure returns (bytes32);
function parseKeys(bytes32[] _keys) internal pure returns (bytes32[]);
}
contract StoreRBAC {
// stores: storeName -> key -> addr -> isAllowed
mapping(uint256 => mapping (uint256 => mapping(address => bool))) private stores;
// store names
uint256 public constant STORE_RBAC = 1;
uint256 public constant STORE_FUNCTIONS = 2;
uint256 public constant STORE_KEYS = 3;
// rbac roles
uint256 public constant RBAC_ROLE_ADMIN = 1; // "admin"
// events
event RoleAdded(uint256 storeName, address addr, uint256 role);
event RoleRemoved(uint256 storeName, address addr, uint256 role);
constructor() public {
addRole(STORE_RBAC, msg.sender, RBAC_ROLE_ADMIN);
}
function hasRole(uint256 storeName, address addr, uint256 role) public view returns (bool) {
return stores[storeName][role][addr];
}
function checkRole(uint256 storeName, address addr, uint256 role) public view {
require(hasRole(storeName, addr, role));
}
function addRole(uint256 storeName, address addr, uint256 role) internal {
stores[storeName][role][addr] = true;
emit RoleAdded(storeName, addr, role);
}
function removeRole(uint256 storeName, address addr, uint256 role) internal {
stores[storeName][role][addr] = false;
emit RoleRemoved(storeName, addr, role);
}
function adminAddRole(uint256 storeName, address addr, uint256 role) onlyAdmin public {
addRole(storeName, addr, role);
}
function adminRemoveRole(uint256 storeName, address addr, uint256 role) onlyAdmin public {
removeRole(storeName, addr, role);
}
modifier onlyRole(uint256 storeName, uint256 role) {
checkRole(storeName, msg.sender, role);
_;
}
modifier onlyAdmin() {
checkRole(STORE_RBAC, msg.sender, RBAC_ROLE_ADMIN);
_;
}
}
contract FunctionProtection is StoreRBAC {
// standard roles
uint256 constant public FN_ROLE_CREATE = 2; // create
uint256 constant public FN_ROLE_UPDATE = 3; // update
uint256 constant public FN_ROLE_REMOVE = 4; // remove
function canCreate() internal view returns (bool) {
return hasRole(STORE_FUNCTIONS, msg.sender, FN_ROLE_CREATE);
}
function canUpdate() internal view returns (bool) {
return hasRole(STORE_FUNCTIONS, msg.sender, FN_ROLE_UPDATE);
}
function canRemove() internal view returns (bool) {
return hasRole(STORE_FUNCTIONS, msg.sender, FN_ROLE_REMOVE);
}
// external functions
function applyAllPermission(address _address) external onlyAdmin {
addRole(STORE_FUNCTIONS, _address, FN_ROLE_CREATE);
addRole(STORE_FUNCTIONS, _address, FN_ROLE_UPDATE);
addRole(STORE_FUNCTIONS, _address, FN_ROLE_REMOVE);
}
}
contract CryptantCrabMarketStore is FunctionProtection {
// Structure of each traded record
struct TradeRecord {
uint256 tokenId;
uint256 auctionId;
uint256 price;
uint48 time;
address owner;
address seller;
}
// Structure of each trading item
struct AuctionItem {
uint256 tokenId;
uint256 basePrice;
address seller;
uint48 startTime;
uint48 endTime;
uint8 state; // 0 - on going, 1 - cancelled, 2 - claimed
uint256[] bidIndexes; // storing bidId
}
struct Bid {
uint256 auctionId;
uint256 price;
uint48 time;
address bidder;
}
// Structure to store withdrawal information
struct WithdrawalRecord {
uint256 auctionId;
uint256 value;
uint48 time;
uint48 callTime;
bool hasWithdrawn;
}
// stores awaiting withdrawal information
mapping(address => WithdrawalRecord[]) public withdrawalList;
// stores last withdrawal index
mapping(address => uint256) public lastWithdrawnIndex;
// All traded records will be stored here
TradeRecord[] public tradeRecords;
// All auctioned items will be stored here
AuctionItem[] public auctionItems;
Bid[] public bidHistory;
event TradeRecordAdded(address indexed seller, address indexed buyer, uint256 tradeId, uint256 price, uint256 tokenId, uint256 indexed auctionId);
event AuctionItemAdded(address indexed seller, uint256 auctionId, uint256 basePrice, uint256 duration, uint256 tokenId);
event AuctionBid(address indexed bidder, address indexed previousBidder, uint256 auctionId, uint256 bidPrice, uint256 bidIndex, uint256 tokenId, uint256 endTime);
event PendingWithdrawalCleared(address indexed withdrawer, uint256 withdrawnAmount);
constructor() public
{
// auctionItems index 0 should be dummy,
// because TradeRecord might not have auctionId
auctionItems.push(AuctionItem(0, 0, address(0), 0, 0, 0, new uint256[](1)));
// tradeRecords index 0 will be dummy
// just to follow the standards skipping the index 0
tradeRecords.push(TradeRecord(0, 0, 0, 0, address(0), address(0)));
// bidHistory index 0 will be dummy
// just to follow the standards skipping the index 0
bidHistory.push(Bid(0, 0, uint48(0), address(0)));
}
// external functions
// getters
function getWithdrawalList(address withdrawer) external view returns (
uint256[] memory _auctionIds,
uint256[] memory _values,
uint256[] memory _times,
uint256[] memory _callTimes,
bool[] memory _hasWithdrawn
) {
WithdrawalRecord[] storage withdrawalRecords = withdrawalList[withdrawer];
_auctionIds = new uint256[](withdrawalRecords.length);
_values = new uint256[](withdrawalRecords.length);
_times = new uint256[](withdrawalRecords.length);
_callTimes = new uint256[](withdrawalRecords.length);
_hasWithdrawn = new bool[](withdrawalRecords.length);
for(uint256 i = 0 ; i < withdrawalRecords.length ; i++) {
WithdrawalRecord storage withdrawalRecord = withdrawalRecords[i];
_auctionIds[i] = withdrawalRecord.auctionId;
_values[i] = withdrawalRecord.value;
_times[i] = withdrawalRecord.time;
_callTimes[i] = withdrawalRecord.callTime;
_hasWithdrawn[i] = withdrawalRecord.hasWithdrawn;
}
}
function getTradeRecord(uint256 _tradeId) external view returns (
uint256 _tokenId,
uint256 _auctionId,
uint256 _price,
uint256 _time,
address _owner,
address _seller
) {
TradeRecord storage _tradeRecord = tradeRecords[_tradeId];
_tokenId = _tradeRecord.tokenId;
_auctionId = _tradeRecord.auctionId;
_price = _tradeRecord.price;
_time = _tradeRecord.time;
_owner = _tradeRecord.owner;
_seller = _tradeRecord.seller;
}
function totalTradeRecords() external view returns (uint256) {
return tradeRecords.length - 1; // need to exclude the dummy
}
function getPricesOfLatestTradeRecords(uint256 amount) external view returns (uint256[] memory _prices) {
_prices = new uint256[](amount);
uint256 startIndex = tradeRecords.length - amount;
for(uint256 i = 0 ; i < amount ; i++) {
_prices[i] = tradeRecords[startIndex + i].price;
}
}
function getAuctionItem(uint256 _auctionId) external view returns (
uint256 _tokenId,
uint256 _basePrice,
address _seller,
uint256 _startTime,
uint256 _endTime,
uint256 _state,
uint256[] _bidIndexes
) {
AuctionItem storage _auctionItem = auctionItems[_auctionId];
_tokenId = _auctionItem.tokenId;
_basePrice = _auctionItem.basePrice;
_seller = _auctionItem.seller;
_startTime = _auctionItem.startTime;
_endTime = _auctionItem.endTime;
_state = _auctionItem.state;
_bidIndexes = _auctionItem.bidIndexes;
}
function getAuctionItems(uint256[] _auctionIds) external view returns (
uint256[] _tokenId,
uint256[] _basePrice,
address[] _seller,
uint256[] _startTime,
uint256[] _endTime,
uint256[] _state,
uint256[] _lastBidId
) {
_tokenId = new uint256[](_auctionIds.length);
_basePrice = new uint256[](_auctionIds.length);
_startTime = new uint256[](_auctionIds.length);
_endTime = new uint256[](_auctionIds.length);
_state = new uint256[](_auctionIds.length);
_lastBidId = new uint256[](_auctionIds.length);
_seller = new address[](_auctionIds.length);
for(uint256 i = 0 ; i < _auctionIds.length ; i++) {
AuctionItem storage _auctionItem = auctionItems[_auctionIds[i]];
_tokenId[i] = (_auctionItem.tokenId);
_basePrice[i] = (_auctionItem.basePrice);
_seller[i] = (_auctionItem.seller);
_startTime[i] = (_auctionItem.startTime);
_endTime[i] = (_auctionItem.endTime);
_state[i] = (_auctionItem.state);
for(uint256 j = _auctionItem.bidIndexes.length - 1 ; j > 0 ; j--) {
if(_auctionItem.bidIndexes[j] > 0) {
_lastBidId[i] = _auctionItem.bidIndexes[j];
break;
}
}
}
}
function totalAuctionItems() external view returns (uint256) {
return auctionItems.length - 1; // need to exclude the dummy
}
function getBid(uint256 _bidId) external view returns (
uint256 _auctionId,
uint256 _price,
uint256 _time,
address _bidder
) {
Bid storage _bid = bidHistory[_bidId];
_auctionId = _bid.auctionId;
_price = _bid.price;
_time = _bid.time;
_bidder = _bid.bidder;
}
function getBids(uint256[] _bidIds) external view returns (
uint256[] _auctionId,
uint256[] _price,
uint256[] _time,
address[] _bidder
) {
_auctionId = new uint256[](_bidIds.length);
_price = new uint256[](_bidIds.length);
_time = new uint256[](_bidIds.length);
_bidder = new address[](_bidIds.length);
for(uint256 i = 0 ; i < _bidIds.length ; i++) {
Bid storage _bid = bidHistory[_bidIds[i]];
_auctionId[i] = _bid.auctionId;
_price[i] = _bid.price;
_time[i] = _bid.time;
_bidder[i] = _bid.bidder;
}
}
// setters
function addTradeRecord
(
uint256 _tokenId,
uint256 _auctionId,
uint256 _price,
uint256 _time,
address _buyer,
address _seller
)
external
returns (uint256 _tradeId)
{
require(canUpdate());
_tradeId = tradeRecords.length;
tradeRecords.push(TradeRecord(_tokenId, _auctionId, _price, uint48(_time), _buyer, _seller));
if(_auctionId > 0) {
auctionItems[_auctionId].state = uint8(2);
}
emit TradeRecordAdded(_seller, _buyer, _tradeId, _price, _tokenId, _auctionId);
}
function addAuctionItem
(
uint256 _tokenId,
uint256 _basePrice,
address _seller,
uint256 _endTime
)
external
returns (uint256 _auctionId)
{
require(canUpdate());
_auctionId = auctionItems.length;
auctionItems.push(AuctionItem(
_tokenId,
_basePrice,
_seller,
uint48(now),
uint48(_endTime),
0,
new uint256[](21)));
emit AuctionItemAdded(_seller, _auctionId, _basePrice, _endTime - now, _tokenId);
}
function updateAuctionTime(uint256 _auctionId, uint256 _time, uint256 _state) external {
require(canUpdate());
AuctionItem storage _auctionItem = auctionItems[_auctionId];
_auctionItem.endTime = uint48(_time);
_auctionItem.state = uint8(_state);
}
function addBidder(uint256 _auctionId, address _bidder, uint256 _price, uint256 _bidIndex) external {
require(canUpdate());
uint256 _bidId = bidHistory.length;
bidHistory.push(Bid(_auctionId, _price, uint48(now), _bidder));
AuctionItem storage _auctionItem = auctionItems[_auctionId];
// find previous bidder
// Max bid index is 20, so maximum loop is 20 times
address _previousBidder = address(0);
for(uint256 i = _auctionItem.bidIndexes.length - 1 ; i > 0 ; i--) {
if(_auctionItem.bidIndexes[i] > 0) {
Bid memory _previousBid = bidHistory[_auctionItem.bidIndexes[i]];
_previousBidder = _previousBid.bidder;
break;
}
}
_auctionItem.bidIndexes[_bidIndex] = _bidId;
emit AuctionBid(_bidder, _previousBidder, _auctionId, _price, _bidIndex, _auctionItem.tokenId, _auctionItem.endTime);
}
function addWithdrawal
(
address _withdrawer,
uint256 _auctionId,
uint256 _value,
uint256 _callTime
)
external
{
require(canUpdate());
WithdrawalRecord memory _withdrawal = WithdrawalRecord(_auctionId, _value, uint48(now), uint48(_callTime), false);
withdrawalList[_withdrawer].push(_withdrawal);
}
function clearPendingWithdrawal(address _withdrawer) external returns (uint256 _withdrawnAmount) {
require(canUpdate());
WithdrawalRecord[] storage _withdrawalList = withdrawalList[_withdrawer];
uint256 _lastWithdrawnIndex = lastWithdrawnIndex[_withdrawer];
for(uint256 i = _lastWithdrawnIndex ; i < _withdrawalList.length ; i++) {
WithdrawalRecord storage _withdrawalRecord = _withdrawalList[i];
_withdrawalRecord.hasWithdrawn = true;
_withdrawnAmount += _withdrawalRecord.value;
}
// update the last withdrawn index so next time will start from this index
lastWithdrawnIndex[_withdrawer] = _withdrawalList.length - 1;
emit PendingWithdrawalCleared(_withdrawer, _withdrawnAmount);
}
}
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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 OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract CryptantCrabBase is Ownable {
GenesisCrabInterface public genesisCrab;
CryptantCrabNFT public cryptantCrabToken;
CryptantCrabStoreInterface public cryptantCrabStorage;
constructor(address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress) public {
// constructor
_setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress);
}
function setAddresses(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress
)
external onlyOwner {
_setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress);
}
function _setAddresses(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress
)
internal
{
if(_genesisCrabAddress != address(0)) {
GenesisCrabInterface genesisCrabContract = GenesisCrabInterface(_genesisCrabAddress);
genesisCrab = genesisCrabContract;
}
if(_cryptantCrabTokenAddress != address(0)) {
CryptantCrabNFT cryptantCrabTokenContract = CryptantCrabNFT(_cryptantCrabTokenAddress);
cryptantCrabToken = cryptantCrabTokenContract;
}
if(_cryptantCrabStorageAddress != address(0)) {
CryptantCrabStoreInterface cryptantCrabStorageContract = CryptantCrabStoreInterface(_cryptantCrabStorageAddress);
cryptantCrabStorage = cryptantCrabStorageContract;
}
}
}
contract CryptantCrabInformant is CryptantCrabBase{
constructor
(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress
)
public
CryptantCrabBase
(
_genesisCrabAddress,
_cryptantCrabTokenAddress,
_cryptantCrabStorageAddress
) {
// constructor
}
function _getCrabData(uint256 _tokenId) internal view returns
(
uint256 _gene,
uint256 _level,
uint256 _exp,
uint256 _mutationCount,
uint256 _trophyCount,
uint256 _heartValue,
uint256 _growthValue
) {
require(cryptantCrabStorage != address(0));
bytes32[] memory keys = new bytes32[](7);
uint256[] memory values;
keys[0] = keccak256(abi.encodePacked(_tokenId, "gene"));
keys[1] = keccak256(abi.encodePacked(_tokenId, "level"));
keys[2] = keccak256(abi.encodePacked(_tokenId, "exp"));
keys[3] = keccak256(abi.encodePacked(_tokenId, "mutationCount"));
keys[4] = keccak256(abi.encodePacked(_tokenId, "trophyCount"));
keys[5] = keccak256(abi.encodePacked(_tokenId, "heartValue"));
keys[6] = keccak256(abi.encodePacked(_tokenId, "growthValue"));
values = cryptantCrabStorage.readUint256s(keys);
// process heart value
uint256 _processedHeartValue;
for(uint256 i = 1 ; i <= 1000 ; i *= 10) {
if(uint256(values[5]) / i % 10 > 0) {
_processedHeartValue += i;
}
}
_gene = values[0];
_level = values[1];
_exp = values[2];
_mutationCount = values[3];
_trophyCount = values[4];
_heartValue = _processedHeartValue;
_growthValue = values[6];
}
function _geneOfCrab(uint256 _tokenId) internal view returns (uint256 _gene) {
require(cryptantCrabStorage != address(0));
_gene = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, "gene")));
}
}
contract CrabManager is CryptantCrabInformant, CrabData {
constructor
(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress
)
public
CryptantCrabInformant
(
_genesisCrabAddress,
_cryptantCrabTokenAddress,
_cryptantCrabStorageAddress
) {
// constructor
}
function getCrabsOfOwner(address _owner) external view returns (uint256[]) {
uint256 _balance = cryptantCrabToken.balanceOf(_owner);
uint256[] memory _tokenIds = new uint256[](_balance);
for(uint256 i = 0 ; i < _balance ; i++) {
_tokenIds[i] = cryptantCrabToken.tokenOfOwnerByIndex(_owner, i);
}
return _tokenIds;
}
function getCrab(uint256 _tokenId) external view returns (
uint256 _gene,
uint256 _level,
uint256 _exp,
uint256 _mutationCount,
uint256 _trophyCount,
uint256 _heartValue,
uint256 _growthValue,
uint256 _fossilType
) {
require(cryptantCrabToken.exists(_tokenId));
(_gene, _level, _exp, _mutationCount, _trophyCount, _heartValue, _growthValue) = _getCrabData(_tokenId);
_fossilType = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, "fossilType")));
}
function getCrabStats(uint256 _tokenId) external view returns (
uint256 _hp,
uint256 _dps,
uint256 _block,
uint256[] _partBonuses,
uint256 _fossilAttribute
) {
require(cryptantCrabToken.exists(_tokenId));
uint256 _gene = _geneOfCrab(_tokenId);
(_hp, _dps, _block) = _getCrabTotalStats(_gene);
_partBonuses = _getCrabPartBonuses(_tokenId);
_fossilAttribute = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, "fossilAttribute")));
}
function _getCrabTotalStats(uint256 _gene) internal view returns (
uint256 _hp,
uint256 _dps,
uint256 _blockRate
) {
CrabPartData[] memory crabPartData = _getCrabPartData(_gene);
for(uint256 i = 0 ; i < crabPartData.length ; i++) {
_hp += crabPartData[i].hp;
_dps += crabPartData[i].dps;
_blockRate += crabPartData[i].blockRate;
}
}
function _getCrabPartBonuses(uint256 _tokenId) internal view returns (uint256[] _partBonuses) {
bytes32[] memory _keys = new bytes32[](4);
_keys[0] = keccak256(abi.encodePacked(_tokenId, uint256(1), "partBonus"));
_keys[1] = keccak256(abi.encodePacked(_tokenId, uint256(2), "partBonus"));
_keys[2] = keccak256(abi.encodePacked(_tokenId, uint256(3), "partBonus"));
_keys[3] = keccak256(abi.encodePacked(_tokenId, uint256(4), "partBonus"));
_partBonuses = cryptantCrabStorage.readUint256s(_keys);
}
function _getCrabPartData(uint256 _gene) internal view returns (CrabPartData[] memory _crabPartData) {
require(cryptantCrabToken != address(0));
uint256[] memory _bodyData;
uint256[] memory _legData;
uint256[] memory _leftClawData;
uint256[] memory _rightClawData;
(_bodyData, _legData, _leftClawData, _rightClawData) = cryptantCrabToken.crabPartDataFromGene(_gene);
_crabPartData = new CrabPartData[](4);
_crabPartData[0] = arrayToCrabPartData(_bodyData);
_crabPartData[1] = arrayToCrabPartData(_legData);
_crabPartData[2] = arrayToCrabPartData(_leftClawData);
_crabPartData[3] = arrayToCrabPartData(_rightClawData);
}
}
contract CryptantCrabPurchasableLaunch is CryptantCrabInformant {
using SafeMath for uint256;
Transmuter public transmuter;
event CrabHatched(address indexed owner, uint256 tokenId, uint256 gene, uint256 specialSkin, uint256 crabPrice, uint256 growthValue);
event CryptantFragmentsAdded(address indexed cryptantOwner, uint256 amount, uint256 newBalance);
event CryptantFragmentsRemoved(address indexed cryptantOwner, uint256 amount, uint256 newBalance);
event Refund(address indexed refundReceiver, uint256 reqAmt, uint256 paid, uint256 refundAmt);
constructor
(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress,
address _transmuterAddress
)
public
CryptantCrabInformant
(
_genesisCrabAddress,
_cryptantCrabTokenAddress,
_cryptantCrabStorageAddress
) {
// constructor
if(_transmuterAddress != address(0)) {
_setTransmuterAddress(_transmuterAddress);
}
}
function setAddresses(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress,
address _transmuterAddress
)
external onlyOwner {
_setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress);
if(_transmuterAddress != address(0)) {
_setTransmuterAddress(_transmuterAddress);
}
}
function _setTransmuterAddress(address _transmuterAddress) internal {
Transmuter _transmuterContract = Transmuter(_transmuterAddress);
transmuter = _transmuterContract;
}
function getCryptantFragments(address _sender) public view returns (uint256) {
return cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_sender, "cryptant")));
}
function createCrab(uint256 _customTokenId, uint256 _crabPrice, uint256 _customGene, uint256 _customSkin, bool _hasLegendary) external onlyOwner {
_createCrab(_customTokenId, _crabPrice, _customGene, _customSkin, _hasLegendary);
}
function _addCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) {
_newBalance = getCryptantFragments(_cryptantOwner).add(_amount);
cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance);
emit CryptantFragmentsAdded(_cryptantOwner, _amount, _newBalance);
}
function _removeCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) {
_newBalance = getCryptantFragments(_cryptantOwner).sub(_amount);
cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance);
emit CryptantFragmentsRemoved(_cryptantOwner, _amount, _newBalance);
}
function _createCrab(uint256 _tokenId, uint256 _crabPrice, uint256 _customGene, uint256 _customSkin, bool _hasLegendary) internal {
uint256[] memory _values = new uint256[](8);
bytes32[] memory _keys = new bytes32[](8);
uint256 _gene;
uint256 _specialSkin;
uint256 _heartValue;
uint256 _growthValue;
if(_customGene == 0) {
(_gene, _specialSkin, _heartValue, _growthValue) = genesisCrab.generateCrabGene(false, _hasLegendary);
} else {
_gene = _customGene;
}
if(_customSkin != 0) {
_specialSkin = _customSkin;
}
(_heartValue, _growthValue) = genesisCrab.generateCrabHeart();
cryptantCrabToken.mintToken(msg.sender, _tokenId, _specialSkin);
// Gene pair
_keys[0] = keccak256(abi.encodePacked(_tokenId, "gene"));
_values[0] = _gene;
// Level pair
_keys[1] = keccak256(abi.encodePacked(_tokenId, "level"));
_values[1] = 1;
// Heart Value pair
_keys[2] = keccak256(abi.encodePacked(_tokenId, "heartValue"));
_values[2] = _heartValue;
// Growth Value pair
_keys[3] = keccak256(abi.encodePacked(_tokenId, "growthValue"));
_values[3] = _growthValue;
// Handling Legendary Bonus
uint256[] memory _partLegendaryBonuses = transmuter.generateBonusForGene(_gene);
// body
_keys[4] = keccak256(abi.encodePacked(_tokenId, uint256(1), "partBonus"));
_values[4] = _partLegendaryBonuses[0];
// legs
_keys[5] = keccak256(abi.encodePacked(_tokenId, uint256(2), "partBonus"));
_values[5] = _partLegendaryBonuses[1];
// left claw
_keys[6] = keccak256(abi.encodePacked(_tokenId, uint256(3), "partBonus"));
_values[6] = _partLegendaryBonuses[2];
// right claw
_keys[7] = keccak256(abi.encodePacked(_tokenId, uint256(4), "partBonus"));
_values[7] = _partLegendaryBonuses[3];
require(cryptantCrabStorage.createUint256s(_keys, _values));
emit CrabHatched(msg.sender, _tokenId, _gene, _specialSkin, _crabPrice, _growthValue);
}
function _refundExceededValue(uint256 _senderValue, uint256 _requiredValue) internal {
uint256 _exceededValue = _senderValue.sub(_requiredValue);
if(_exceededValue > 0) {
msg.sender.transfer(_exceededValue);
emit Refund(msg.sender, _requiredValue, _senderValue, _exceededValue);
}
}
}
contract CryptantInformant is CryptantCrabInformant {
using SafeMath for uint256;
event CryptantFragmentsAdded(address indexed cryptantOwner, uint256 amount, uint256 newBalance);
event CryptantFragmentsRemoved(address indexed cryptantOwner, uint256 amount, uint256 newBalance);
constructor
(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress
)
public
CryptantCrabInformant
(
_genesisCrabAddress,
_cryptantCrabTokenAddress,
_cryptantCrabStorageAddress
) {
// constructor
}
function getCryptantFragments(address _sender) public view returns (uint256) {
return cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_sender, "cryptant")));
}
function _addCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) {
_newBalance = getCryptantFragments(_cryptantOwner).add(_amount);
cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance);
emit CryptantFragmentsAdded(_cryptantOwner, _amount, _newBalance);
}
function _removeCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) {
_newBalance = getCryptantFragments(_cryptantOwner).sub(_amount);
cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance);
emit CryptantFragmentsRemoved(_cryptantOwner, _amount, _newBalance);
}
}
contract Transmuter is CryptantInformant, GeneSurgeon, Randomable, LevelCalculator {
event Xenografted(address indexed tokenOwner, uint256 recipientTokenId, uint256 donorTokenId, uint256 oldPartGene, uint256 newPartGene, uint256 oldPartBonus, uint256 newPartBonus, uint256 xenograftPart);
event Mutated(address indexed tokenOwner, uint256 tokenId, uint256 partIndex, uint256 oldGene, uint256 newGene, uint256 oldPartBonus, uint256 newPartBonus, uint256 mutationCount);
/**
* @dev Pre-generated keys to save gas
* keys are generated with:
* NORMAL_FOSSIL_RELIC_PERCENTAGE = bytes4(keccak256("normalFossilRelicPercentage")) = 0xcaf6fae2
* PIONEER_FOSSIL_RELIC_PERCENTAGE = bytes4(keccak256("pioneerFossilRelicPercentage")) = 0x04988c65
* LEGENDARY_FOSSIL_RELIC_PERCENTAGE = bytes4(keccak256("legendaryFossilRelicPercentage")) = 0x277e613a
* FOSSIL_ATTRIBUTE_COUNT = bytes4(keccak256("fossilAttributesCount")) = 0x06c475be
* LEGENDARY_BONUS_COUNT = bytes4(keccak256("legendaryBonusCount")) = 0x45025094
* LAST_PIONEER_TOKEN_ID = bytes4(keccak256("lastPioneerTokenId")) = 0xe562bae2
*/
bytes4 internal constant NORMAL_FOSSIL_RELIC_PERCENTAGE = 0xcaf6fae2;
bytes4 internal constant PIONEER_FOSSIL_RELIC_PERCENTAGE = 0x04988c65;
bytes4 internal constant LEGENDARY_FOSSIL_RELIC_PERCENTAGE = 0x277e613a;
bytes4 internal constant FOSSIL_ATTRIBUTE_COUNT = 0x06c475be;
bytes4 internal constant LEGENDARY_BONUS_COUNT = 0x45025094;
bytes4 internal constant LAST_PIONEER_TOKEN_ID = 0xe562bae2;
mapping(bytes4 => uint256) internal internalUintVariable;
// elements => legendary set index of that element
mapping(uint256 => uint256[]) internal legendaryPartIndex;
constructor
(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress
)
public
CryptantInformant
(
_genesisCrabAddress,
_cryptantCrabTokenAddress,
_cryptantCrabStorageAddress
) {
// constructor
// default values for relic percentages
// normal crab relic is set to 5%
_setUint(NORMAL_FOSSIL_RELIC_PERCENTAGE, 5000);
// pioneer crab relic is set to 50%
_setUint(PIONEER_FOSSIL_RELIC_PERCENTAGE, 50000);
// legendary crab part relic is set to increase by 50%
_setUint(LEGENDARY_FOSSIL_RELIC_PERCENTAGE, 50000);
// The max number of attributes types
// Every fossil will have 1 attribute
_setUint(FOSSIL_ATTRIBUTE_COUNT, 6);
// The max number of bonus types for legendary
// Every legendary will have 1 bonus
_setUint(LEGENDARY_BONUS_COUNT, 5);
// The last pioneer token ID to be referred as Pioneer
_setUint(LAST_PIONEER_TOKEN_ID, 1121);
}
function setPartIndex(uint256 _element, uint256[] _partIndexes) external onlyOwner {
legendaryPartIndex[_element] = _partIndexes;
}
function getPartIndexes(uint256 _element) external view onlyOwner returns (uint256[] memory _partIndexes){
_partIndexes = legendaryPartIndex[_element];
}
function getUint(bytes4 key) external view returns (uint256 value) {
value = _getUint(key);
}
function setUint(bytes4 key, uint256 value) external onlyOwner {
_setUint(key, value);
}
function _getUint(bytes4 key) internal view returns (uint256 value) {
value = internalUintVariable[key];
}
function _setUint(bytes4 key, uint256 value) internal {
internalUintVariable[key] = value;
}
function xenograft(uint256 _recipientTokenId, uint256 _donorTokenId, uint256 _xenograftPart) external {
// get crab gene of both token
// make sure both token is not fossil
// replace the recipient part with donor part
// mark donor as fosil
// fosil will generate 1 attr
// 3% of fosil will have relic
// deduct 10 cryptant
require(_xenograftPart != 1); // part cannot be body (part index = 1)
require(cryptantCrabToken.ownerOf(_recipientTokenId) == msg.sender); // check ownership of both token
require(cryptantCrabToken.ownerOf(_donorTokenId) == msg.sender);
// due to stack too deep, need to use an array
// to represent all the variables
uint256[] memory _intValues = new uint256[](11);
_intValues[0] = getCryptantFragments(msg.sender);
// _intValues[0] = ownedCryptant
// _intValues[1] = donorPartBonus
// _intValues[2] = recipientGene
// _intValues[3] = donorGene
// _intValues[4] = recipientPart
// _intValues[5] = donorPart
// _intValues[6] = relicPercentage
// _intValues[7] = fossilType
// _intValues[8] = recipientExistingPartBonus
// _intValues[9] = recipientLevel
// _intValues[10] = recipientExp
// perform transplant requires 5 cryptant
require(_intValues[0] >= 5000);
// make sure both tokens are not fossil
uint256[] memory _values;
bytes32[] memory _keys = new bytes32[](6);
_keys[0] = keccak256(abi.encodePacked(_recipientTokenId, "fossilType"));
_keys[1] = keccak256(abi.encodePacked(_donorTokenId, "fossilType"));
_keys[2] = keccak256(abi.encodePacked(_donorTokenId, _xenograftPart, "partBonus"));
_keys[3] = keccak256(abi.encodePacked(_recipientTokenId, _xenograftPart, "partBonus"));
_keys[4] = keccak256(abi.encodePacked(_recipientTokenId, "level"));
_keys[5] = keccak256(abi.encodePacked(_recipientTokenId, "exp"));
_values = cryptantCrabStorage.readUint256s(_keys);
require(_values[0] == 0);
require(_values[1] == 0);
_intValues[1] = _values[2];
_intValues[8] = _values[3];
// _values[5] = recipient Exp
// _values[4] = recipient Level
_intValues[9] = _values[4];
_intValues[10] = _values[5];
// Increase Exp
_intValues[10] += 8;
// check if crab level up
uint256 _expRequired = expRequiredToReachLevel(_intValues[9] + 1);
if(_intValues[10] >=_expRequired) {
// increase level
_intValues[9] += 1;
// carry forward extra exp
_intValues[10] -= _expRequired;
emit LevelUp(msg.sender, _recipientTokenId, _intValues[9], _intValues[10]);
} else {
emit ExpGained(msg.sender, _recipientTokenId, _intValues[9], _intValues[10]);
}
// start performing Xenograft
_intValues[2] = _geneOfCrab(_recipientTokenId);
_intValues[3] = _geneOfCrab(_donorTokenId);
// recipientPart
_intValues[4] = _intValues[2] / crabPartMultiplier[_xenograftPart] % 1000;
_intValues[5] = _intValues[3] / crabPartMultiplier[_xenograftPart] % 1000;
int256 _partDiff = int256(_intValues[4]) - int256(_intValues[5]);
_intValues[2] = uint256(int256(_intValues[2]) - (_partDiff * int256(crabPartMultiplier[_xenograftPart])));
_values = new uint256[](6);
_keys = new bytes32[](6);
// Gene pair
_keys[0] = keccak256(abi.encodePacked(_recipientTokenId, "gene"));
_values[0] = _intValues[2];
// Fossil Attribute
_keys[1] = keccak256(abi.encodePacked(_donorTokenId, "fossilAttribute"));
_values[1] = _generateRandomNumber(bytes32(_intValues[2] + _intValues[3] + _xenograftPart), _getUint(FOSSIL_ATTRIBUTE_COUNT)) + 1;
// intVar1 will now use to store relic percentage variable
if(isLegendaryPart(_intValues[3], 1)) {
// if body part is legendary 100% become relic
_intValues[7] = 2;
} else {
// Relic percentage will differ depending on the crab type / rarity
_intValues[6] = _getUint(NORMAL_FOSSIL_RELIC_PERCENTAGE);
if(_donorTokenId <= _getUint(LAST_PIONEER_TOKEN_ID)) {
_intValues[6] = _getUint(PIONEER_FOSSIL_RELIC_PERCENTAGE);
}
if(isLegendaryPart(_intValues[3], 2) ||
isLegendaryPart(_intValues[3], 3) || isLegendaryPart(_intValues[3], 4)) {
_intValues[6] += _getUint(LEGENDARY_FOSSIL_RELIC_PERCENTAGE);
}
// Fossil Type
// 1 = Normal Fossil
// 2 = Relic Fossil
_intValues[7] = 1;
if(_generateRandomNumber(bytes32(_intValues[3] + _xenograftPart), 100000) < _intValues[6]) {
_intValues[7] = 2;
}
}
_keys[2] = keccak256(abi.encodePacked(_donorTokenId, "fossilType"));
_values[2] = _intValues[7];
// Part Attribute
_keys[3] = keccak256(abi.encodePacked(_recipientTokenId, _xenograftPart, "partBonus"));
_values[3] = _intValues[1];
// Recipient Level
_keys[4] = keccak256(abi.encodePacked(_recipientTokenId, "level"));
_values[4] = _intValues[9];
// Recipient Exp
_keys[5] = keccak256(abi.encodePacked(_recipientTokenId, "exp"));
_values[5] = _intValues[10];
require(cryptantCrabStorage.updateUint256s(_keys, _values));
_removeCryptantFragments(msg.sender, 5000);
emit Xenografted(msg.sender, _recipientTokenId, _donorTokenId, _intValues[4], _intValues[5], _intValues[8], _intValues[1], _xenograftPart);
}
function mutate(uint256 _tokenId, uint256 _partIndex) external {
// token must be owned by sender
require(cryptantCrabToken.ownerOf(_tokenId) == msg.sender);
// body part cannot mutate
require(_partIndex > 1 && _partIndex < 5);
// here not checking if sender has enough cryptant
// is because _removeCryptantFragments uses safeMath
// to do subtract, so it will revert if it's not enough
_removeCryptantFragments(msg.sender, 1000);
bytes32[] memory _keys = new bytes32[](5);
_keys[0] = keccak256(abi.encodePacked(_tokenId, "gene"));
_keys[1] = keccak256(abi.encodePacked(_tokenId, "level"));
_keys[2] = keccak256(abi.encodePacked(_tokenId, "exp"));
_keys[3] = keccak256(abi.encodePacked(_tokenId, "mutationCount"));
_keys[4] = keccak256(abi.encodePacked(_tokenId, _partIndex, "partBonus"));
uint256[] memory _values = new uint256[](5);
(_values[0], _values[1], _values[2], _values[3], , , ) = _getCrabData(_tokenId);
uint256[] memory _partsGene = new uint256[](5);
uint256 i;
for(i = 1 ; i <= 4 ; i++) {
_partsGene[i] = _values[0] / crabPartMultiplier[i] % 1000;
}
// mutate starts from 3%, max is 20% which is 170 mutations
if(_values[3] > 170) {
_values[3] = 170;
}
uint256 newPartGene = genesisCrab.mutateCrabPart(_partIndex, _partsGene[_partIndex], (30 + _values[3]) * 100);
//generate the new gene
uint256 _oldPartBonus = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, _partIndex, "partBonus")));
uint256 _partGene; // this variable will be reused by oldGene
uint256 _newGene;
for(i = 1 ; i <= 4 ; i++) {
_partGene = _partsGene[i];
if(i == _partIndex) {
_partGene = newPartGene;
}
_newGene += _partGene * crabPartMultiplier[i];
}
if(isLegendaryPart(_newGene, _partIndex)) {
_values[4] = _generateRandomNumber(bytes32(_newGene + _partIndex + _tokenId), _getUint(LEGENDARY_BONUS_COUNT)) + 1;
}
// Reuse partGene as old gene
_partGene = _values[0];
// New Gene
_values[0] = _newGene;
// Increase Exp
_values[2] += 8;
// check if crab level up
uint256 _expRequired = expRequiredToReachLevel(_values[1] + 1);
if(_values[2] >=_expRequired) {
// increase level
_values[1] += 1;
// carry forward extra exp
_values[2] -= _expRequired;
emit LevelUp(msg.sender, _tokenId, _values[1], _values[2]);
} else {
emit ExpGained(msg.sender, _tokenId, _values[1], _values[2]);
}
// Increase Mutation Count
_values[3] += 1;
require(cryptantCrabStorage.updateUint256s(_keys, _values));
emit Mutated(msg.sender, _tokenId, _partIndex, _partGene, _newGene, _oldPartBonus, _values[4], _values[3]);
}
function generateBonusForGene(uint256 _gene) external view returns (uint256[] _bonuses) {
_bonuses = new uint256[](4);
uint256[] memory _elements = extractElementsFromGene(_gene);
uint256[] memory _parts = extractPartsFromGene(_gene);
uint256[] memory _legendaryParts;
for(uint256 i = 0 ; i < 4 ; i++) {
_legendaryParts = legendaryPartIndex[_elements[i]];
for(uint256 j = 0 ; j < _legendaryParts.length ; j++) {
if(_legendaryParts[j] == _parts[i]) {
// generate the bonus number and add it into the _bonuses array
_bonuses[i] = _generateRandomNumber(bytes32(_gene + i), _getUint(LEGENDARY_BONUS_COUNT)) + 1;
break;
}
}
}
}
/**
* @dev checks if the specified part of the given gene is a legendary part or not
* returns true if its a legendary part, false otherwise.
* @param _gene full body gene to be checked on
* @param _part partIndex ranging from 1 = body, 2 = legs, 3 = left claw, 4 = right claw
*/
function isLegendaryPart(uint256 _gene, uint256 _part) internal view returns (bool) {
uint256[] memory _legendaryParts = legendaryPartIndex[extractElementsFromGene(_gene)[_part - 1]];
for(uint256 i = 0 ; i < _legendaryParts.length ; i++) {
if(_legendaryParts[i] == extractPartsFromGene(_gene)[_part - 1]) {
return true;
}
}
return false;
}
}
contract Withdrawable is Ownable {
address public withdrawer;
/**
* @dev Throws if called by any account other than the withdrawer.
*/
modifier onlyWithdrawer() {
require(msg.sender == withdrawer);
_;
}
function setWithdrawer(address _newWithdrawer) external onlyOwner {
withdrawer = _newWithdrawer;
}
/**
* @dev withdraw the specified amount of ether from contract.
* @param _amount the amount of ether to withdraw. Units in wei.
*/
function withdraw(uint256 _amount) external onlyWithdrawer returns(bool) {
require(_amount <= address(this).balance);
withdrawer.transfer(_amount);
return true;
}
}
contract CryptantCrabMarket is CryptantCrabPurchasableLaunch, GeneSurgeon, Randomable, Withdrawable {
event Purchased(address indexed owner, uint256 amount, uint256 cryptant, uint256 refund);
event ReferralPurchase(address indexed referral, uint256 rewardAmount, address buyer);
event CrabOnSaleStarted(address indexed seller, uint256 tokenId, uint256 sellingPrice, uint256 marketId, uint256 gene);
event CrabOnSaleCancelled(address indexed seller, uint256 tokenId, uint256 marketId);
event Traded(address indexed seller, address indexed buyer, uint256 tokenId, uint256 tradedPrice, uint256 marketId); // Trade Type 0 = Purchase
struct MarketItem {
uint256 tokenId;
uint256 sellingPrice;
address seller;
uint8 state; // 1 - on going, 2 - cancelled, 3 - completed
}
PrizePool public prizePool;
/**
* @dev Pre-generated keys to save gas
* keys are generated with:
* MARKET_PRICE_UPDATE_PERIOD = bytes4(keccak256("marketPriceUpdatePeriod")) = 0xf1305a10
* CURRENT_TOKEN_ID = bytes4(keccak256("currentTokenId")) = 0x21339464
* REFERRAL_CUT = bytes4(keccak256("referralCut")) = 0x40b0b13e
* PURCHASE_PRIZE_POOL_CUT = bytes4(keccak256("purchasePrizePoolCut")) = 0x7625c58a
* EXCHANGE_PRIZE_POOL_CUT = bytes4(keccak256("exchangePrizePoolCut")) = 0xb9e1adb0
* EXCHANGE_DEVELOPER_CUT = bytes4(keccak256("exchangeDeveloperCut")) = 0xfe9ad0eb
* LAST_TRANSACTION_PERIOD = bytes4(keccak256("lastTransactionPeriod")) = 0x1a01d5bb
* LAST_TRANSACTION_PRICE = bytes4(keccak256("lastTransactionPrice")) = 0xf14adb6a
*/
bytes4 internal constant MARKET_PRICE_UPDATE_PERIOD = 0xf1305a10;
bytes4 internal constant CURRENT_TOKEN_ID = 0x21339464;
bytes4 internal constant REFERRAL_CUT = 0x40b0b13e;
bytes4 internal constant PURCHASE_PRIZE_POOL_CUT = 0x7625c58a;
bytes4 internal constant EXCHANGE_PRIZE_POOL_CUT = 0xb9e1adb0;
bytes4 internal constant EXCHANGE_DEVELOPER_CUT = 0xfe9ad0eb;
bytes4 internal constant LAST_TRANSACTION_PERIOD = 0x1a01d5bb;
bytes4 internal constant LAST_TRANSACTION_PRICE = 0xf14adb6a;
/**
* @dev The first 25 trading crab price will be fixed to 0.3 ether.
* This only applies to crab bought from developer.
* Crab on auction will depends on the price set by owner.
*/
uint256 constant public initialCrabTradingPrice = 300 finney;
// The initial cryptant price will be fixed to 0.03 ether.
// It will changed to dynamic price after 25 crabs traded.
// 1000 Cryptant Fragment = 1 Cryptant.
uint256 constant public initialCryptantFragmentTradingPrice = 30 szabo;
mapping(bytes4 => uint256) internal internalUintVariable;
// All traded price will be stored here
uint256[] public tradedPrices;
// All auctioned items will be stored here
MarketItem[] public marketItems;
// PrizePool key, default value is 0xadd5d43f
// 0xadd5d43f = bytes4(keccak256(bytes("firstPrizePool")));
bytes4 public currentPrizePool = 0xadd5d43f;
constructor
(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress,
address _transmuterAddress,
address _prizePoolAddress
)
public
CryptantCrabPurchasableLaunch
(
_genesisCrabAddress,
_cryptantCrabTokenAddress,
_cryptantCrabStorageAddress,
_transmuterAddress
) {
// constructor
if(_prizePoolAddress != address(0)) {
_setPrizePoolAddress(_prizePoolAddress);
}
// set the initial token id
_setUint(CURRENT_TOKEN_ID, 1121);
// The number of seconds that the market will stay at fixed price.
// Default set to 4 hours
_setUint(MARKET_PRICE_UPDATE_PERIOD, 14400);
// The percentage of referral cut
// Default set to 10%
_setUint(REFERRAL_CUT, 10000);
// The percentage of price pool cut when purchase a new crab
// Default set to 20%
_setUint(PURCHASE_PRIZE_POOL_CUT, 20000);
// The percentage of prize pool cut when market exchange traded
// Default set to 2%
_setUint(EXCHANGE_PRIZE_POOL_CUT, 2000);
// The percentage of developer cut
// Default set to 2.8%
_setUint(EXCHANGE_DEVELOPER_CUT, 2800);
// to prevent marketId = 0
// put a dummy value for it
marketItems.push(MarketItem(0, 0, address(0), 0));
}
function _setPrizePoolAddress(address _prizePoolAddress) internal {
PrizePool _prizePoolContract = PrizePool(_prizePoolAddress);
prizePool = _prizePoolContract;
}
function setAddresses(
address _genesisCrabAddress,
address _cryptantCrabTokenAddress,
address _cryptantCrabStorageAddress,
address _transmuterAddress,
address _prizePoolAddress
)
external onlyOwner {
_setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress);
if(_transmuterAddress != address(0)) {
_setTransmuterAddress(_transmuterAddress);
}
if(_prizePoolAddress != address(0)) {
_setPrizePoolAddress(_prizePoolAddress);
}
}
function setCurrentPrizePool(bytes4 _newPrizePool) external onlyOwner {
currentPrizePool = _newPrizePool;
}
function getUint(bytes4 key) external view returns (uint256 value) {
value = _getUint(key);
}
function setUint(bytes4 key, uint256 value) external onlyOwner {
_setUint(key, value);
}
function _getUint(bytes4 key) internal view returns (uint256 value) {
value = internalUintVariable[key];
}
function _setUint(bytes4 key, uint256 value) internal {
internalUintVariable[key] = value;
}
function purchase(uint256 _crabAmount, uint256 _cryptantFragmentAmount, address _referral) external payable {
require(_crabAmount >= 0 && _crabAmount <= 10 );
require(_cryptantFragmentAmount >= 0 && _cryptantFragmentAmount <= 10000);
require(!(_crabAmount == 0 && _cryptantFragmentAmount == 0));
require(_cryptantFragmentAmount % 1000 == 0);
require(msg.sender != _referral);
// check if ether payment is enough
uint256 _singleCrabPrice = getCurrentCrabPrice();
uint256 _totalCrabPrice = _singleCrabPrice * _crabAmount;
uint256 _totalCryptantPrice = getCurrentCryptantFragmentPrice() * _cryptantFragmentAmount;
uint256 _cryptantFragmentsGained = _cryptantFragmentAmount;
// free 2 cryptant when purchasing 10
if(_cryptantFragmentsGained == 10000) {
_cryptantFragmentsGained += 2000;
}
uint256 _totalPrice = _totalCrabPrice + _totalCryptantPrice;
uint256 _value = msg.value;
require(_value >= _totalPrice);
// Purchase 10 crabs will have 1 crab with legendary part
// Default value for _crabWithLegendaryPart is just a unreacable number
uint256 _currentTokenId = _getUint(CURRENT_TOKEN_ID);
uint256 _crabWithLegendaryPart = 100;
if(_crabAmount == 10) {
// decide which crab will have the legendary part
_crabWithLegendaryPart = _generateRandomNumber(bytes32(_currentTokenId), 10);
}
for(uint256 i = 0 ; i < _crabAmount ; i++) {
// 5000 ~ 5500 is gift token
// so if hit 5000 will skip to 5500 onwards
if(_currentTokenId == 5000) {
_currentTokenId = 5500;
}
_currentTokenId++;
_createCrab(_currentTokenId, _singleCrabPrice, 0, 0, _crabWithLegendaryPart == i);
tradedPrices.push(_singleCrabPrice);
}
if(_cryptantFragmentsGained > 0) {
_addCryptantFragments(msg.sender, (_cryptantFragmentsGained));
}
_setUint(CURRENT_TOKEN_ID, _currentTokenId);
// Refund exceeded value
_refundExceededValue(_value, _totalPrice);
// If there's referral, will transfer the referral reward to the referral
if(_referral != address(0)) {
uint256 _referralReward = _totalPrice * _getUint(REFERRAL_CUT) / 100000;
_referral.transfer(_referralReward);
emit ReferralPurchase(_referral, _referralReward, msg.sender);
}
// Send prize pool cut to prize pool
uint256 _prizePoolAmount = _totalPrice * _getUint(PURCHASE_PRIZE_POOL_CUT) / 100000;
prizePool.increasePrizePool.value(_prizePoolAmount)(currentPrizePool);
_setUint(LAST_TRANSACTION_PERIOD, now / _getUint(MARKET_PRICE_UPDATE_PERIOD));
_setUint(LAST_TRANSACTION_PRICE, _singleCrabPrice);
emit Purchased(msg.sender, _crabAmount, _cryptantFragmentsGained, _value - _totalPrice);
}
function getCurrentPeriod() external view returns (uint256 _now, uint256 _currentPeriod) {
_now = now;
_currentPeriod = now / _getUint(MARKET_PRICE_UPDATE_PERIOD);
}
function getCurrentCrabPrice() public view returns (uint256) {
if(totalCrabTraded() > 25) {
uint256 _lastTransactionPeriod = _getUint(LAST_TRANSACTION_PERIOD);
uint256 _lastTransactionPrice = _getUint(LAST_TRANSACTION_PRICE);
if(_lastTransactionPeriod == now / _getUint(MARKET_PRICE_UPDATE_PERIOD) && _lastTransactionPrice != 0) {
return _lastTransactionPrice;
} else {
uint256 totalPrice;
for(uint256 i = 1 ; i <= 15 ; i++) {
totalPrice += tradedPrices[tradedPrices.length - i];
}
// the actual calculation here is:
// average price = totalPrice / 15
return totalPrice / 15;
}
} else {
return initialCrabTradingPrice;
}
}
function getCurrentCryptantFragmentPrice() public view returns (uint256 _price) {
if(totalCrabTraded() > 25) {
// real calculation is 1 Cryptant = 10% of currentCrabPrice
// should be written as getCurrentCrabPrice() * 10 / 100 / 1000
return getCurrentCrabPrice() * 10 / 100000;
} else {
return initialCryptantFragmentTradingPrice;
}
}
// After pre-sale crab tracking (excluding fossil transactions)
function totalCrabTraded() public view returns (uint256) {
return tradedPrices.length;
}
function sellCrab(uint256 _tokenId, uint256 _sellingPrice) external {
require(cryptantCrabToken.ownerOf(_tokenId) == msg.sender);
require(_sellingPrice >= 50 finney && _sellingPrice <= 100 ether);
marketItems.push(MarketItem(_tokenId, _sellingPrice, msg.sender, 1));
// escrow
cryptantCrabToken.transferFrom(msg.sender, address(this), _tokenId);
uint256 _gene = _geneOfCrab(_tokenId);
emit CrabOnSaleStarted(msg.sender, _tokenId, _sellingPrice, marketItems.length - 1, _gene);
}
function cancelOnSaleCrab(uint256 _marketId) external {
MarketItem storage marketItem = marketItems[_marketId];
// Only able to cancel on sale Item
require(marketItem.state == 1);
// Set Market Item state to 2(Cancelled)
marketItem.state = 2;
// Only owner can cancel on sale item
require(marketItem.seller == msg.sender);
// Release escrow to the owner
cryptantCrabToken.transferFrom(address(this), msg.sender, marketItem.tokenId);
emit CrabOnSaleCancelled(msg.sender, marketItem.tokenId, _marketId);
}
function buyCrab(uint256 _marketId) external payable {
MarketItem storage marketItem = marketItems[_marketId];
require(marketItem.state == 1); // make sure the sale is on going
require(marketItem.sellingPrice == msg.value);
require(marketItem.seller != msg.sender);
cryptantCrabToken.safeTransferFrom(address(this), msg.sender, marketItem.tokenId);
uint256 _developerCut = msg.value * _getUint(EXCHANGE_DEVELOPER_CUT) / 100000;
uint256 _prizePoolCut = msg.value * _getUint(EXCHANGE_PRIZE_POOL_CUT) / 100000;
uint256 _sellerAmount = msg.value - _developerCut - _prizePoolCut;
marketItem.seller.transfer(_sellerAmount);
// Send prize pool cut to prize pool
prizePool.increasePrizePool.value(_prizePoolCut)(currentPrizePool);
uint256 _fossilType = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(marketItem.tokenId, "fossilType")));
if(_fossilType > 0) {
tradedPrices.push(marketItem.sellingPrice);
}
marketItem.state = 3;
_setUint(LAST_TRANSACTION_PERIOD, now / _getUint(MARKET_PRICE_UPDATE_PERIOD));
_setUint(LAST_TRANSACTION_PRICE, getCurrentCrabPrice());
emit Traded(marketItem.seller, msg.sender, marketItem.tokenId, marketItem.sellingPrice, _marketId);
}
function() public payable {
revert();
}
}
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
view
public
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
view
public
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
onlyOwner
public
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
onlyOwner
public
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
contract PrizePool is Ownable, Whitelist, HasNoEther {
event PrizePoolIncreased(uint256 amountIncreased, bytes4 prizePool, uint256 currentAmount);
event WinnerAdded(address winner, bytes4 prizeTitle, uint256 claimableAmount);
event PrizedClaimed(address winner, bytes4 prizeTitle, uint256 claimedAmount);
// prizePool key => prizePool accumulated amount
// this is just to track how much a prizePool has
mapping(bytes4 => uint256) prizePools;
// winner's address => prize title => amount
// prize title itself need to be able to determine
// the prize pool it is from
mapping(address => mapping(bytes4 => uint256)) winners;
constructor() public {
}
function increasePrizePool(bytes4 _prizePool) external payable onlyIfWhitelisted(msg.sender) {
prizePools[_prizePool] += msg.value;
emit PrizePoolIncreased(msg.value, _prizePool, prizePools[_prizePool]);
}
function addWinner(address _winner, bytes4 _prizeTitle, uint256 _claimableAmount) external onlyIfWhitelisted(msg.sender) {
winners[_winner][_prizeTitle] = _claimableAmount;
emit WinnerAdded(_winner, _prizeTitle, _claimableAmount);
}
function claimPrize(bytes4 _prizeTitle) external {
uint256 _claimableAmount = winners[msg.sender][_prizeTitle];
require(_claimableAmount > 0);
msg.sender.transfer(_claimableAmount);
winners[msg.sender][_prizeTitle] = 0;
emit PrizedClaimed(msg.sender, _prizeTitle, _claimableAmount);
}
function claimableAmount(address _winner, bytes4 _prizeTitle) external view returns (uint256 _claimableAmount) {
_claimableAmount = winners[_winner][_prizeTitle];
}
function prizePoolTotal(bytes4 _prizePool) external view returns (uint256 _prizePoolTotal) {
_prizePoolTotal = prizePools[_prizePool];
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
contract ERC721Basic is ERC165 {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
contract CryptantCrabNFT is ERC721Token, Whitelist, CrabData, GeneSurgeon {
event CrabPartAdded(uint256 hp, uint256 dps, uint256 blockAmount);
event GiftTransfered(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event DefaultMetadataURIChanged(string newUri);
/**
* @dev Pre-generated keys to save gas
* keys are generated with:
* CRAB_BODY = bytes4(keccak256("crab_body")) = 0xc398430e
* CRAB_LEG = bytes4(keccak256("crab_leg")) = 0x889063b1
* CRAB_LEFT_CLAW = bytes4(keccak256("crab_left_claw")) = 0xdb6290a2
* CRAB_RIGHT_CLAW = bytes4(keccak256("crab_right_claw")) = 0x13453f89
*/
bytes4 internal constant CRAB_BODY = 0xc398430e;
bytes4 internal constant CRAB_LEG = 0x889063b1;
bytes4 internal constant CRAB_LEFT_CLAW = 0xdb6290a2;
bytes4 internal constant CRAB_RIGHT_CLAW = 0x13453f89;
/**
* @dev Stores all the crab data
*/
mapping(bytes4 => mapping(uint256 => CrabPartData[])) internal crabPartData;
/**
* @dev Mapping from tokenId to its corresponding special skin
* tokenId with default skin will not be stored.
*/
mapping(uint256 => uint256) internal crabSpecialSkins;
/**
* @dev default MetadataURI
*/
string public defaultMetadataURI = "https://www.cryptantcrab.io/md/";
constructor(string _name, string _symbol) public ERC721Token(_name, _symbol) {
// constructor
initiateCrabPartData();
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist.
* Will return the token's metadata URL if it has one,
* otherwise will just return base on the default metadata URI
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
string memory _uri = tokenURIs[_tokenId];
if(bytes(_uri).length == 0) {
_uri = getMetadataURL(bytes(defaultMetadataURI), _tokenId);
}
return _uri;
}
/**
* @dev Returns the data of a specific parts
* @param _partIndex the part to retrieve. 1 = Body, 2 = Legs, 3 = Left Claw, 4 = Right Claw
* @param _element the element of part to retrieve. 1 = Fire, 2 = Earth, 3 = Metal, 4 = Spirit, 5 = Water
* @param _setIndex the set index of for the specified part. This will starts from 1.
*/
function dataOfPart(uint256 _partIndex, uint256 _element, uint256 _setIndex) public view returns (uint256[] memory _resultData) {
bytes4 _key;
if(_partIndex == 1) {
_key = CRAB_BODY;
} else if(_partIndex == 2) {
_key = CRAB_LEG;
} else if(_partIndex == 3) {
_key = CRAB_LEFT_CLAW;
} else if(_partIndex == 4) {
_key = CRAB_RIGHT_CLAW;
} else {
revert();
}
CrabPartData storage _crabPartData = crabPartData[_key][_element][_setIndex];
_resultData = crabPartDataToArray(_crabPartData);
}
/**
* @dev Gift(Transfer) a token to another address. Caller must be token owner
* @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 giftToken(address _from, address _to, uint256 _tokenId) external {
safeTransferFrom(_from, _to, _tokenId);
emit GiftTransfered(_from, _to, _tokenId);
}
/**
* @dev External function to mint a new token, for whitelisted address only.
* Reverts if the given token ID already exists
* @param _tokenOwner address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
* @param _skinId the skin ID to be applied for all the token minted
*/
function mintToken(address _tokenOwner, uint256 _tokenId, uint256 _skinId) external onlyIfWhitelisted(msg.sender) {
super._mint(_tokenOwner, _tokenId);
if(_skinId > 0) {
crabSpecialSkins[_tokenId] = _skinId;
}
}
/**
* @dev Returns crab data base on the gene provided
* @param _gene the gene info where crab data will be retrieved base on it
* @return 4 uint arrays:
* 1st Array = Body's Data
* 2nd Array = Leg's Data
* 3rd Array = Left Claw's Data
* 4th Array = Right Claw's Data
*/
function crabPartDataFromGene(uint256 _gene) external view returns (
uint256[] _bodyData,
uint256[] _legData,
uint256[] _leftClawData,
uint256[] _rightClawData
) {
uint256[] memory _parts = extractPartsFromGene(_gene);
uint256[] memory _elements = extractElementsFromGene(_gene);
_bodyData = dataOfPart(1, _elements[0], _parts[0]);
_legData = dataOfPart(2, _elements[1], _parts[1]);
_leftClawData = dataOfPart(3, _elements[2], _parts[2]);
_rightClawData = dataOfPart(4, _elements[3], _parts[3]);
}
/**
* @dev For developer to add new parts, notice that this is the only method to add crab data
* so that developer can add extra content. there's no other method for developer to modify
* the data. This is to assure token owner actually owns their data.
* @param _partIndex the part to add. 1 = Body, 2 = Legs, 3 = Left Claw, 4 = Right Claw
* @param _element the element of part to add. 1 = Fire, 2 = Earth, 3 = Metal, 4 = Spirit, 5 = Water
* @param _partDataArray data of the parts.
*/
function setPartData(uint256 _partIndex, uint256 _element, uint256[] _partDataArray) external onlyOwner {
CrabPartData memory _partData = arrayToCrabPartData(_partDataArray);
bytes4 _key;
if(_partIndex == 1) {
_key = CRAB_BODY;
} else if(_partIndex == 2) {
_key = CRAB_LEG;
} else if(_partIndex == 3) {
_key = CRAB_LEFT_CLAW;
} else if(_partIndex == 4) {
_key = CRAB_RIGHT_CLAW;
}
// if index 1 is empty will fill at index 1
if(crabPartData[_key][_element][1].hp == 0 && crabPartData[_key][_element][1].dps == 0) {
crabPartData[_key][_element][1] = _partData;
} else {
crabPartData[_key][_element].push(_partData);
}
emit CrabPartAdded(_partDataArray[0], _partDataArray[1], _partDataArray[2]);
}
/**
* @dev Updates the default metadata URI
* @param _defaultUri the new metadata URI
*/
function setDefaultMetadataURI(string _defaultUri) external onlyOwner {
defaultMetadataURI = _defaultUri;
emit DefaultMetadataURIChanged(_defaultUri);
}
/**
* @dev Updates the metadata URI for existing token
* @param _tokenId the tokenID that metadata URI to be changed
* @param _uri the new metadata URI for the specified token
*/
function setTokenURI(uint256 _tokenId, string _uri) external onlyIfWhitelisted(msg.sender) {
_setTokenURI(_tokenId, _uri);
}
/**
* @dev Returns the special skin of the provided tokenId
* @param _tokenId cryptant crab's tokenId
* @return Special skin belongs to the _tokenId provided.
* 0 will be returned if no special skin found.
*/
function specialSkinOfTokenId(uint256 _tokenId) external view returns (uint256) {
return crabSpecialSkins[_tokenId];
}
/**
* @dev This functions will adjust the length of crabPartData
* so that when adding data the index can start with 1.
* Reason of doing this is because gene cannot have parts with index 0.
*/
function initiateCrabPartData() internal {
require(crabPartData[CRAB_BODY][1].length == 0);
for(uint256 i = 1 ; i <= 5 ; i++) {
crabPartData[CRAB_BODY][i].length = 2;
crabPartData[CRAB_LEG][i].length = 2;
crabPartData[CRAB_LEFT_CLAW][i].length = 2;
crabPartData[CRAB_RIGHT_CLAW][i].length = 2;
}
}
/**
* @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,
* or has been whitelisted by contract owner
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) || whitelist(_spender);
}
/**
* @dev Will merge the uri and tokenId together.
* @param _uri URI to be merge. This will be the first part of the result URL.
* @param _tokenId tokenID to be merge. This will be the last part of the result URL.
* @return the merged urL
*/
function getMetadataURL(bytes _uri, uint256 _tokenId) internal pure returns (string) {
uint256 _tmpTokenId = _tokenId;
uint256 _tokenLength;
// Getting the length(number of digits) of token ID
do {
_tokenLength++;
_tmpTokenId /= 10;
} while (_tmpTokenId > 0);
// creating a byte array with the length of URL + token digits
bytes memory _result = new bytes(_uri.length + _tokenLength);
// cloning the uri bytes into the result bytes
for(uint256 i = 0 ; i < _uri.length ; i ++) {
_result[i] = _uri[i];
}
// appending the tokenId to the end of the result bytes
uint256 lastIndex = _result.length - 1;
for(_tmpTokenId = _tokenId ; _tmpTokenId > 0 ; _tmpTokenId /= 10) {
_result[lastIndex--] = byte(48 + _tmpTokenId % 10);
}
return string(_result);
}
} | check if ether payment is enough free 2 cryptant when purchasing 10 decide which crab will have the legendary part 5000 ~ 5500 is gift token so if hit 5000 will skip to 5500 onwards If there&39;s referral, will transfer the referral reward to the referral | function purchase(uint256 _crabAmount, uint256 _cryptantFragmentAmount, address _referral) external payable {
require(_crabAmount >= 0 && _crabAmount <= 10 );
require(_cryptantFragmentAmount >= 0 && _cryptantFragmentAmount <= 10000);
require(!(_crabAmount == 0 && _cryptantFragmentAmount == 0));
require(_cryptantFragmentAmount % 1000 == 0);
require(msg.sender != _referral);
uint256 _singleCrabPrice = getCurrentCrabPrice();
uint256 _totalCrabPrice = _singleCrabPrice * _crabAmount;
uint256 _totalCryptantPrice = getCurrentCryptantFragmentPrice() * _cryptantFragmentAmount;
uint256 _cryptantFragmentsGained = _cryptantFragmentAmount;
if(_cryptantFragmentsGained == 10000) {
_cryptantFragmentsGained += 2000;
}
uint256 _totalPrice = _totalCrabPrice + _totalCryptantPrice;
uint256 _value = msg.value;
require(_value >= _totalPrice);
uint256 _crabWithLegendaryPart = 100;
if(_crabAmount == 10) {
_crabWithLegendaryPart = _generateRandomNumber(bytes32(_currentTokenId), 10);
}
for(uint256 i = 0 ; i < _crabAmount ; i++) {
if(_currentTokenId == 5000) {
_currentTokenId = 5500;
}
_currentTokenId++;
_createCrab(_currentTokenId, _singleCrabPrice, 0, 0, _crabWithLegendaryPart == i);
tradedPrices.push(_singleCrabPrice);
}
if(_cryptantFragmentsGained > 0) {
_addCryptantFragments(msg.sender, (_cryptantFragmentsGained));
}
_setUint(CURRENT_TOKEN_ID, _currentTokenId);
if(_referral != address(0)) {
uint256 _referralReward = _totalPrice * _getUint(REFERRAL_CUT) / 100000;
_referral.transfer(_referralReward);
emit ReferralPurchase(_referral, _referralReward, msg.sender);
}
prizePool.increasePrizePool.value(_prizePoolAmount)(currentPrizePool);
_setUint(LAST_TRANSACTION_PERIOD, now / _getUint(MARKET_PRICE_UPDATE_PERIOD));
_setUint(LAST_TRANSACTION_PRICE, _singleCrabPrice);
emit Purchased(msg.sender, _crabAmount, _cryptantFragmentsGained, _value - _totalPrice);
}
| 10,814,646 |
/**
*Submitted for verification at Etherscan.io on 2021-05-24
*/
/**
*Submitted for verification at Etherscan.io on 2021-03-31
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner,"ERR_AUTHORIZED_OWNER_ONLY");
_;
}
/**
* @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),"ERR_ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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)));
}
}
/**
* @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);
}
contract RemitPresale is Ownable{
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
uint256 public minDeposit;
uint256 public maxDeposit;
uint256 public tokenPrice;
uint256 public startTime;
uint256 public endTime;
uint256 public capAmount;
uint256 public totalInvestment;
uint256 public totalRemitPurchased;
bool public isPaused;
address public walletAddress;
IERC20 public remit;
constructor(address _tokenAddress,address _walletAddress)public{
require(_walletAddress != address(0));
require(_tokenAddress != address(0));
remit = IERC20(_tokenAddress);
walletAddress = _walletAddress;
}
//Mappings
EnumerableSet.AddressSet private depositers;
mapping(address => uint256)public claimableAmount;
//Events
event TokenPurchase(
address indexed beneficiary,
address indexed purchaser,
uint256 value,
uint256 amount
);
event TokenClaimed(
address indexed purchaser,
uint256 timestamp,
uint256 amount
);
/*
* @dev To start the pre sale
*
* @param
* '_endTime' - specifies the end time of pre sale
*/
function startPresale(uint256 _endTime)external onlyOwner{
require(minDeposit != 0 && maxDeposit != 0 && tokenPrice != 0 ,"ERR_SET_MINDEPOSIT_MAXDEPOSIT_PRICE_FIRST");
require(capAmount != 0,"ERR_CAP_AMOUNT_CANNOT_BE_0");
require(_endTime > now , "ERR_PRESALE_ENDTIME_CANNOT_BE_CURRENT_TIME");
startTime = now;
endTime = _endTime;
isPaused = false;
}
/*
* @dev To buy the tokens
*
*/
function buyToken()public payable {
address _buyer = msg.sender;
uint256 _ethDeposited = msg.value;
require(startTime != 0,"ERR_PRESALE_HAS_NOT_STARTED");
require(now < endTime,"ERR_PRESALE_ENDED");
require(!isPaused,"ERR_PRESALE_IS_PAUSED");
require(_ethDeposited >= minDeposit && _ethDeposited <= maxDeposit,"ERR_AMOUNT_TOO_SMALL_OR_TOO_BIG");
require(totalInvestment.add(_ethDeposited) <= capAmount,"ERR_CAP_HIT_CANNOT_ACCEPT");
require(remit.balanceOf(address(this)) != 0,"ERR_TOKENS_SOLD_OUT");
uint256 amount = _calculateTokens(_ethDeposited);
if(!depositers.contains(_buyer)) depositers.add(_buyer);
claimableAmount[_buyer] = claimableAmount[_buyer].add(amount);
totalInvestment = totalInvestment.add(_ethDeposited);
emit TokenPurchase(address(this),_buyer,_ethDeposited,amount);
}
/*
* @dev To claim the tokens
*
*/
function claim()external {
address _buyer = msg.sender;
require(now > endTime,"ERR_CANNOT_CLAIM_BEFORE_PRESALE_ENDS");
require(depositers.contains(_buyer),"ERR_NOT_AUTHORIZED_TO_CLAIM");
require(claimableAmount[_buyer] != 0,"ERR_NO_AMOUNT_TO_CLAIM");
uint256 amount = claimableAmount[_buyer];
require(remit.transfer(_buyer,amount),"ERR_TRANSFER_FAILED");
claimableAmount[_buyer] = 0;
depositers.remove(_buyer);
emit TokenClaimed(_buyer,now,amount);
}
//To get number of tokens relevant to eth deposited
function _calculateTokens(uint256 _ethDeposited)internal returns(uint256){
uint256 tokens = (_ethDeposited).mul(1e18).div(tokenPrice);
totalRemitPurchased = totalRemitPurchased.add(tokens);
return tokens;
}
/*
* @dev To withdraw the eth deposited
*
*/
function withdrawDepositedEth()external onlyOwner{
(bool success,) = walletAddress.call{value:totalInvestment}(new bytes(0));
require(success,"ERR_TRANSFER_FAILED");
totalInvestment = 0;
}
/*
* @dev To set minium deposit limit
*
* @param
* '_minamount' - specifies minimum amount to be deposited
*/
function setMinDeposit(uint256 _minamount)external onlyOwner{
minDeposit = _minamount;
}
/*
* @dev To set maximum deposit limit
*
* @param
* '_maxamount' - specifies maximum amount can be deposited
*/
function setMaxDeposit(uint256 _maxamount)external onlyOwner{
maxDeposit = _maxamount;
}
/*
* @dev To set token price
*
* @param
* '_price' - specifies token price
*/
function setPrice(uint _price)external onlyOwner{
tokenPrice = _price;
}
/*
* @dev To set cap limit
*
* @param
* '_limit' - specifies cap limit
*/
function setCap(uint _limit)external onlyOwner{
capAmount = _limit;
}
/*
* @dev To set wallet address where eth will be transferred
*
* @param
* '_walletAddress' - specifies address of user
*/
function setWalletAddress(address _walletAddress)external onlyOwner{
walletAddress = _walletAddress;
}
/*
* @dev To pauseor unpause the pre sale
*
* @param
* '_val' - specifies the boolean value
*/
function isPausable(bool _val)external onlyOwner{
isPaused = _val;
}
receive () payable external {
buyToken();
}
fallback () payable external {
buyToken();
}
} | To claim the tokens/ | function claim()external {
address _buyer = msg.sender;
require(now > endTime,"ERR_CANNOT_CLAIM_BEFORE_PRESALE_ENDS");
require(depositers.contains(_buyer),"ERR_NOT_AUTHORIZED_TO_CLAIM");
require(claimableAmount[_buyer] != 0,"ERR_NO_AMOUNT_TO_CLAIM");
uint256 amount = claimableAmount[_buyer];
require(remit.transfer(_buyer,amount),"ERR_TRANSFER_FAILED");
claimableAmount[_buyer] = 0;
depositers.remove(_buyer);
emit TokenClaimed(_buyer,now,amount);
}
| 11,932,038 |
// Copyright 2021 Cartesi Pte. Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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 TurnBasedGame
/// @author Milton Jonathan
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@cartesi/descartes-sdk/contracts/DescartesInterface.sol";
import "@cartesi/logger/contracts/Logger.sol";
import "@cartesi/util/contracts/InstantiatorImpl.sol";
import "./TurnBasedGameContext.sol";
import "./TurnBasedGameUtil.sol";
/// @title TurnBasedGame
/// @notice Generic contract for handling turn-based games validated by Descartes computations
contract TurnBasedGame is InstantiatorImpl {
// Address for the allowed token provider
address allowedERC20Address;
using TurnBasedGameContext for GameContext;
// Descartes instance used for triggering verified computations
DescartesInterface descartes;
// Logger instance used for storing data in the event history
Logger logger;
// index of an empty chunk of data stored in the logger
uint256 emptyDataLogIndex;
// turn data log2size fixed as 12 (4K)
uint8 constant turnChunkLog2Size = 12;
// game instances
mapping(uint256 => GameContext) internal instances;
/// @notice Constructor
/// @param _allowedERC20Address address of the ERC20 compatible token provider
/// @param _descartesAddress address of the Descartes contract
/// @param _loggerAddress address of the Logger contract
constructor(
address _allowedERC20Address,
address _descartesAddress,
address _loggerAddress
) {
allowedERC20Address = _allowedERC20Address;
descartes = DescartesInterface(_descartesAddress);
logger = Logger(_loggerAddress);
// stores an empty chunk of data in the logger and records its index
bytes8[] memory emptyData = new bytes8[](1);
bytes32 logHash = logger.calculateMerkleRootFromData(turnChunkLog2Size, emptyData);
emptyDataLogIndex = logger.getLogIndex(logHash);
}
/// @notice Starts a new game
/// @param _gameTemplateHash template hash for the Cartesi Machine computation that verifies the game (identifies the game computation/logic)
/// @param _gameMetadata game-specific initial metadata/parameters
/// @param _gameValidators addresses of the validator nodes that will run a Descartes verification should it be needed
/// @param _gameTimeout global timeout for game activity in seconds, after which the game may be terminated (zero means there is no timeout limit)
/// @param _gameERC20Address address for a ERC20 compatible token provider
/// @param _players addresses of the players involved
/// @param _playerFunds funds/balances that each player is bringing into the game
/// @param _playerInfos game-specific information for each player
/// @return index of the game instance
function startGame(
bytes32 _gameTemplateHash,
bytes memory _gameMetadata,
address[] memory _gameValidators,
uint256 _gameTimeout,
address _gameERC20Address,
address[] memory _players,
uint256[] memory _playerFunds,
bytes[] memory _playerInfos
) public returns (uint256) {
// ensures that the token provider is the allowed one
require(_gameERC20Address == allowedERC20Address, "Unexpected token provider");
// tranfer tokens to game contract
transferTokensToGameAccount(IERC20(_gameERC20Address), msg.sender, _playerFunds);
// creates new context
GameContext storage context = instances[currentIndex];
context.gameTemplateHash = _gameTemplateHash;
context.gameMetadata = _gameMetadata;
context.gameValidators = _gameValidators;
context.gameTimeout = _gameTimeout;
context.gameERC20Address = _gameERC20Address;
context.players = _players;
context.playerFunds = _playerFunds;
context.playerInfos = _playerInfos;
context.startTimestamp = block.timestamp;
// emits event for new game
emit TurnBasedGameContext.GameReady(currentIndex, context);
active[currentIndex] = true;
return currentIndex++;
}
/// @notice Transfer tokens to the game contract account
/// @param _tokenProvider ERC20 compatible token provider instance
/// @param _holder account from where tokens will be transferred to the game
/// @param _playerFunds amount of tokens from each player
function transferTokensToGameAccount(
IERC20 _tokenProvider,
address _holder,
uint256[] memory _playerFunds
) public {
uint256 tokensToTransfer;
for (uint256 i = 0; i < _playerFunds.length; i++) {
tokensToTransfer += _playerFunds[i];
}
_tokenProvider.transferFrom(_holder, address(this), tokensToTransfer);
}
/// @notice Returns game context
/// @param _index index identifying the game
/// @return GameContext struct for the specified game
function getContext(uint256 _index) public view onlyInstantiated(_index) returns (GameContext memory) {
return instances[_index];
}
/// @notice Submits a new turn for a given game
/// @param _index index identifying the game
/// @param _turnIndex a sequential number for the turn, which must be equal to the last submitted turn's index + 1
/// @param _nextPlayer address of a player responsible for next turn (can be empty, in which case no player will be held accountable for a timeout)
/// @param _playerStake amount of tokens at stake after the turn
/// @param _data game-specific turn data (array of 64-bit words)
function submitTurn(
uint256 _index,
uint256 _turnIndex,
address _nextPlayer,
uint256 _playerStake,
bytes calldata _data
) public onlyActive(_index) {
GameContext storage context = instances[_index];
// before accepting submitted turn, checks for a timeout
if (context.claimTimeout(_index)) {
// game ended by timeout
deactivate(_index);
} else {
// submits turn
context.submitTurn(_index, _turnIndex, _nextPlayer, _playerStake, _data, logger, turnChunkLog2Size);
}
}
/// @notice Challenges game state, triggering a verification by a Descartes computation
/// @param _index index identifying the game
/// @param _message message associated with the challenge (e.g., alleged cause)
/// @return index of the Descartes computation
function challengeGame(uint256 _index, string memory _message) public onlyActive(_index) returns (uint256) {
GameContext storage context = instances[_index];
return context.challengeGame(_index, _message, descartes, logger, turnChunkLog2Size, emptyDataLogIndex);
}
/// @notice Claims game has ended due to a timeout.
/// @param _index index identifying the game
function claimTimeout(uint256 _index) public onlyActive(_index) {
GameContext storage context = instances[_index];
if (context.claimTimeout(_index)) {
// game ended by timeout
deactivate(_index);
}
}
/// @notice Claims game has ended with the provided result (share of locked funds)
/// @param _index index identifying the game
/// @param _fundsShare result of the game given as a distribution of the funds previously locked
function claimResult(uint256 _index, uint256[] memory _fundsShare) public onlyActive(_index) {
GameContext storage context = instances[_index];
// before accepting claim, checks for a timeout
if (context.claimTimeout(_index)) {
// game ended by timeout
deactivate(_index);
} else {
// claims result
context.claimResult(_index, _fundsShare);
}
}
/// @notice Confirms game results previously claimed
/// @param _index index identifying the game
function confirmResult(uint256 _index) public onlyActive(_index) {
GameContext storage context = instances[_index];
// before accepting confirmation, checks for a timeout
if (context.claimTimeout(_index)) {
// game ended by timeout
deactivate(_index);
} else {
// confirms claimed result
bool isConsensus = context.confirmResult();
if (isConsensus) {
// all players agree: apply claimed result and end game
context.applyResult(_index, context.claimedFundsShare);
deactivate(_index);
}
}
}
/// @notice Applies the result of a game verified by Descartes, transferring funds according to the Descartes computation output
/// @param _index index identifying the game
function applyVerificationResult(uint256 _index) public onlyActive(_index) {
GameContext storage context = instances[_index];
context.applyVerificationResult(_index, descartes);
deactivate(_index);
}
/// @notice Indicates whether a given player is concerned about a game
/// @param _index index identifying the game
/// @param _player a player's address
/// @return true if the player is concerned about the game, false otherwise
function isConcerned(uint256 _index, address _player) public view override onlyInstantiated(_index) returns (bool) {
GameContext storage context = instances[_index];
return context.isConcerned(_player);
}
/// @notice Returns state of the instance for offchain usage concerning given validator.
/// @param _index index identifying the game
/// @return _isDescartesInstantiated whether an offchain Descartes computation has been instantiated for this game
function getState(uint256 _index, address)
public
view
onlyInstantiated(_index)
returns (bool _isDescartesInstantiated)
{
GameContext storage context = instances[_index];
return context.isDescartesInstantiated;
}
/// @notice Retrieves sub-instances of the game (required method for Instantiator, used by offchain dispatcher code).
/// @param _index index identifying the game
function getSubInstances(uint256 _index, address)
public
view
override
onlyInstantiated(_index)
returns (address[] memory _addresses, uint256[] memory _indices)
{
GameContext storage context = instances[_index];
if (context.isDescartesInstantiated) {
// sub-instance is the associated Descartes computation
address[] memory addresses = new address[](1);
uint256[] memory indices = new uint256[](1);
addresses[0] = address(descartes);
indices[0] = context.descartesIndex;
return (addresses, indices);
} else {
// no sub-instances
return (new address[](0), new uint256[](0));
}
}
}
| Indicates whether a given player is concerned about a game _index index identifying the game _player a player's address return true if the player is concerned about the game, false otherwise | function isConcerned(uint256 _index, address _player) public view override onlyInstantiated(_index) returns (bool) {
GameContext storage context = instances[_index];
return context.isConcerned(_player);
}
| 12,706,977 |
./partial_match/1/0xCFc2d34b63d0e2fC623eEb4c0d7943e341140810/sources/MorpheusGameController.sol | After claimRewards, players can manualy claim them part of MGT Re entry secure | function claimMyReward() public {
require(_myRewardTokens[msg.sender] > 0, "You don't have any token to claim");
uint256 _myTempRewardTokens = _myRewardTokens[msg.sender];
_myRewardTokens[msg.sender] = 0;
morpheus.transfer(msg.sender, _myTempRewardTokens);
}
| 16,054,973 |
./full_match/1/0x898746F421e8951B9e11db1728797Ddbe6874d01/sources/contracts/Token.sol | ___ ___ ___ _ ___ ___ _____ ___ ___ _ _ | _ | __| __| | | __/ __|_ _|_ _/ _ \| \| | | | _|| _|| |__| _| (__ | | | | (_) | .` | |_|_|___|_| |____|___\___| |_| |___\___/|_|\_| | function excludeAccount(address account) external onlyManager {
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
| 17,023,891 |
./full_match/5/0xAd2580AaD69F1E09A50c2f84393F2c69412CF6E2/sources/contracts/Contract.sol | Set MAX TRX Amount Set MAX Transaction Amount in Token | function setMaxTransactionAmount(uint256 newValue) external onlyOwner {
require(newValue != maxTxAmount, "Ares Token: Cannot update maxTxAmount to same value");
emit MaxTransactionAmountChange(newValue, maxTxAmount);
maxTxAmount = newValue;
}
| 1,878,888 |
./full_match/1/0x49F5d49ce4e4e335B14f5FB9a8DC942B26FCe0ac/sources/contracts/TWMStaking.sol | Admin function to authorise the contract address/ | function authorise(address toAuth) public onlyOwner {
_authorised[toAuth] = true;
authorisedLog.push(toAuth);
}
| 16,481,409 |
./partial_match/1/0xD16176b39530538C42E8E2Dd0c81ec26C2929668/sources/GSNMultiSigWalletWithDailyLimit.sol | Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached. transactionId Transaction ID. | function executeTransaction(uint transactionId)
public
ownerExists(_msgSender())
confirmed(transactionId, _msgSender())
notExecuted(transactionId)
{
Transaction storage txn = transactions[transactionId];
bool _confirmed = isConfirmed(transactionId);
if (_confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) {
txn.executed = true;
if (!_confirmed)
spentToday += txn.value;
if (external_call(txn.destination, txn.value, txn.data.length, txn.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
if (!_confirmed)
spentToday -= txn.value;
}
}
}
| 3,609,067 |
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | 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/node/settings/RocketDAONodeTrustedSettingsInterface.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 RocketDAONodeTrustedSettings is RocketBase, RocketDAONodeTrustedSettingsInterface {
// The namespace for a particular group of settings
bytes32 settingNameSpace;
// Only allow updating from the DAO proposals contract
modifier onlyDAONodeTrustedProposal() {
// If this contract has been initialised, only allow access from the proposals contract
if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAONodeTrustedProposals") == msg.sender, "Only DAO Node Trusted Proposals contract can update a setting");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) {
// Apply the setting namespace
settingNameSpace = keccak256(abi.encodePacked("dao.trustednodes.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 onlyDAONodeTrustedProposal {
// 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 onlyDAONodeTrustedProposal {
// Update setting now
setBool(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 "./RocketDAONodeTrustedSettings.sol";
import "../../../../interface/dao/node/settings/RocketDAONodeTrustedSettingsMembersInterface.sol";
// The Trusted Node DAO Members
contract RocketDAONodeTrustedSettingsMembers is RocketDAONodeTrustedSettings, RocketDAONodeTrustedSettingsMembersInterface {
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketDAONodeTrustedSettings(_rocketStorageAddress, "members") {
// Set version
version = 1;
// Initialize settings on deployment
if(!getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) {
// Init settings
setSettingUint("members.quorum", 0.51 ether); // Member quorum threshold that must be met for proposals to pass (51%)
setSettingUint("members.rplbond", 1750 ether); // Bond amount required for a new member to join (in RPL)
setSettingUint("members.minipool.unbonded.max", 30); // The amount of unbonded minipool validators members can make (these validators are only used if no regular bonded validators are available)
setSettingUint("members.minipool.unbonded.min.fee", 0.8 ether); // Node fee must be over this percentage of the maximum fee before validator members are allowed to make unbonded pools (80%)
setSettingUint("members.challenge.cooldown", 7 days); // How long a member must wait before performing another challenge in seconds
setSettingUint("members.challenge.window", 7 days); // How long a member has to respond to a challenge in seconds
setSettingUint("members.challenge.cost", 1 ether); // How much it costs a non-member to challenge a members node. It's free for current members to challenge other members.
// Settings initialised
setBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")), true);
}
}
/*** Set Uint *****************************************/
// Update a setting, overrides inherited setting method with extra checks for this contract
function setSettingUint(string memory _settingPath, uint256 _value) override public onlyDAONodeTrustedProposal {
// Some safety guards for certain settings
if(keccak256(abi.encodePacked(_settingPath)) == keccak256(abi.encodePacked("members.quorum"))) require(_value > 0 ether && _value <= 0.9 ether, "Quorum setting must be > 0 & <= 90%");
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
// Getters
// The member proposal quorum threshold for this DAO
function getQuorum() override external view returns (uint256) {
return getSettingUint("members.quorum");
}
// Amount of RPL needed for a new member
function getRPLBond() override external view returns (uint256) {
return getSettingUint("members.rplbond");
}
// The amount of unbonded minipool validators members can make (these validators are only used if no regular bonded validators are available)
function getMinipoolUnbondedMax() override external view returns (uint256) {
return getSettingUint("members.minipool.unbonded.max");
}
// Node fee must be over this percentage of the maximum fee before validator members are allowed to make unbonded pools
function getMinipoolUnbondedMinFee() override external view returns (uint256) {
return getSettingUint('members.minipool.unbonded.min.fee');
}
// How long a member must wait before making consecutive challenges in seconds
function getChallengeCooldown() override external view returns (uint256) {
return getSettingUint("members.challenge.cooldown");
}
// The window available to meet any node challenges in seconds
function getChallengeWindow() override external view returns (uint256) {
return getSettingUint("members.challenge.window");
}
// How much it costs a non-member to challenge a members node. It's free for current members to challenge other members.
function getChallengeCost() override external view returns (uint256) {
return getSettingUint("members.challenge.cost");
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | 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 RocketDAONodeTrustedSettingsInterface {
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;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | 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 RocketDAONodeTrustedSettingsMembersInterface {
function getQuorum() external view returns (uint256);
function getRPLBond() external view returns(uint256);
function getMinipoolUnbondedMax() external view returns(uint256);
function getMinipoolUnbondedMinFee() external view returns(uint256);
function getChallengeCooldown() external view returns(uint256);
function getChallengeWindow() external view returns(uint256);
function getChallengeCost() external view returns(uint256);
} | Update a setting, overrides inherited setting method with extra checks for this contract Some safety guards for certain settings Update setting now | function setSettingUint(string memory _settingPath, uint256 _value) override public onlyDAONodeTrustedProposal {
if(keccak256(abi.encodePacked(_settingPath)) == keccak256(abi.encodePacked("members.quorum"))) require(_value > 0 ether && _value <= 0.9 ether, "Quorum setting must be > 0 & <= 90%");
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
| 14,852,778 |
./partial_match/1/0xfd2fFEAD16Fa2d90d55269a6f1586A203b97b123/sources/CelebToken.sol | See {IERC721Metadata-tokenURI}./ | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
| 2,587,452 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.1;
interface IMoonCatAcclimator {
function getApproved(uint256 tokenId) external view returns (address);
function isApprovedForAll(address owner, address operator) external view returns (bool);
function ownerOf(uint256 tokenId) external view returns (address);
function balanceOf(address _owner) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
interface IMoonCatRescue {
function rescueOrder(uint256 tokenId) external view returns (bytes5);
function catOwners(bytes5 catId) external view returns (address);
}
interface IReverseResolver {
function claim(address owner) external returns (bytes32);
}
interface IRegistry {
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external;
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function owner(bytes32 node) external view returns (address);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IERC721 {
function safeTransferFrom(address from, address to, uint256 tokenId) external;
}
/**
* @title MoonCatResolver
* @notice ENS Resolver for MoonCat subdomains
* @dev Auto-updates to point to the owner of that specific MoonCat
*/
contract MoonCatResolver {
/* External Contracts */
IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69);
IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6);
/* State */
mapping(bytes32 => uint256) internal NamehashMapping; // ENS namehash => Rescue ID of MoonCat
mapping(uint256 => mapping(uint256 => bytes)) internal MultichainMapping; // Rescue ID of MoonCat => Multichain ID => value
mapping(uint256 => mapping(string => string)) internal TextKeyMapping; // Rescue ID of MoonCat => text record key => value
mapping(uint256 => bytes) internal ContentsMapping; // Rescue ID of MoonCat => content hash
mapping(uint256 => address) internal lastAnnouncedAddress; // Rescue ID of MoonCat => address that was last emitted in an AddrChanged Event
address payable public owner;
bytes32 immutable public rootHash;
string public ENSDomain; // Reference for the ENS domain this contract resolves
string public avatarBaseURI = "eip155:1/erc721:0xc3f733ca98e0dad0386979eb96fb1722a1a05e69/";
uint64 public defaultTTL = 86400;
// For string-matching on a specific text key
uint256 constant internal avatarKeyLength = 6;
bytes32 constant internal avatarKeyHash = keccak256("avatar");
/* Events */
event AddrChanged(bytes32 indexed node, address a);
event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress);
event TextChanged(bytes32 indexed node, string indexedKey, string key);
event ContenthashChanged(bytes32 indexed node, bytes hash);
/* Modifiers */
modifier onlyOwner () {
require(msg.sender == owner, "Only Owner");
_;
}
modifier onlyMoonCatOwner (uint256 rescueOrder) {
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated");
require(msg.sender == MCA.ownerOf(rescueOrder), "Not MoonCat's owner");
_;
}
/**
* @dev Deploy resolver contract.
*/
constructor(bytes32 _rootHash, string memory _ENSDomain){
owner = payable(msg.sender);
rootHash = _rootHash;
ENSDomain = _ENSDomain;
// https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address
IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148)
.claim(msg.sender);
}
/**
* @dev Allow current `owner` to transfer ownership to another address
*/
function transferOwnership (address payable newOwner) public onlyOwner {
owner = newOwner;
}
/**
* @dev Update the "avatar" value that gets set by default.
*/
function setAvatarBaseUrl(string calldata url) public onlyOwner {
avatarBaseURI = url;
}
/**
* @dev Update the default TTL value.
*/
function setDefaultTTL(uint64 newTTL) public onlyOwner {
defaultTTL = newTTL;
}
/**
* @dev Pass ownership of a subnode of the contract's root hash to the owner.
*/
function giveControl(bytes32 nodeId) public onlyOwner {
IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e).setSubnodeOwner(rootHash, nodeId, owner);
}
/**
* @dev Rescue ERC20 assets sent directly to this contract.
*/
function withdrawForeignERC20(address tokenContract) public onlyOwner {
IERC20 token = IERC20(tokenContract);
token.transfer(owner, token.balanceOf(address(this)));
}
/**
* @dev Rescue ERC721 assets sent directly to this contract.
*/
function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner {
IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId);
}
/**
* @dev ERC165 support for ENS resolver interface
* https://docs.ens.domains/contract-developer-guide/writing-a-resolver
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == 0x01ffc9a7 // supportsInterface call itself
|| interfaceID == 0x3b3b57de // EIP137: ENS resolver
|| interfaceID == 0xf1cb7e06 // EIP2304: Multichain addresses
|| interfaceID == 0x59d1d43c // EIP634: ENS text records
|| interfaceID == 0xbc1c58d1 // EIP1577: contenthash
;
}
/**
* @dev For a given ENS Node ID, return the Ethereum address it points to.
* EIP137 core functionality
*/
function addr(bytes32 nodeID) public view returns (address) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
address actualOwner = MCA.ownerOf(rescueOrder);
if (
MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA) ||
actualOwner != lastAnnouncedAddress[rescueOrder]
) {
return address(0); // Not Acclimated/Announced; return zero (per spec)
} else {
return lastAnnouncedAddress[rescueOrder];
}
}
/**
* @dev For a given ENS Node ID, return an address on a different blockchain it points to.
* EIP2304 functionality
*/
function addr(bytes32 nodeID, uint256 coinType) public view returns (bytes memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
if (MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) {
return bytes(''); // Not Acclimated; return zero (per spec)
}
if (coinType == 60) {
// Ethereum address
return abi.encodePacked(addr(nodeID));
} else {
return MultichainMapping[rescueOrder][coinType];
}
}
/**
* @dev For a given ENS Node ID, set it to point to an address on a different blockchain.
* EIP2304 functionality
*/
function setAddr(bytes32 nodeID, uint256 coinType, bytes calldata newAddr) public {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
setAddr(rescueOrder, coinType, newAddr);
}
/**
* @dev For a given MoonCat rescue order, set the subdomains associated with it to point to an address on a different blockchain.
*/
function setAddr(uint256 rescueOrder, uint256 coinType, bytes calldata newAddr) public onlyMoonCatOwner(rescueOrder) {
if (coinType == 60) {
// Ethereum address
announceMoonCat(rescueOrder);
return;
}
emit AddressChanged(getSubdomainNameHash(uint2str(rescueOrder)), coinType, newAddr);
emit AddressChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), coinType, newAddr);
MultichainMapping[rescueOrder][coinType] = newAddr;
}
/**
* @dev For a given ENS Node ID, return the value associated with a given text key.
* If the key is "avatar", and the matching value is not explicitly set, a url pointing to the MoonCat's image is returned
* EIP634 functionality
*/
function text(bytes32 nodeID, string calldata key) public view returns (string memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
string memory value = TextKeyMapping[rescueOrder][key];
if (bytes(value).length > 0) {
// This value has been set explicitly; return that
return value;
}
// Check if there's a default value for this key
bytes memory keyBytes = bytes(key);
if (keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){
// Avatar default
return string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));
}
// No default; just return the empty string
return value;
}
/**
* @dev Update a text record for a specific subdomain.
* EIP634 functionality
*/
function setText(bytes32 nodeID, string calldata key, string calldata value) public {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
setText(rescueOrder, key, value);
}
/**
* @dev Update a text record for subdomains owned by a specific MoonCat rescue order.
*/
function setText(uint256 rescueOrder, string calldata key, string calldata value) public onlyMoonCatOwner(rescueOrder) {
bytes memory keyBytes = bytes(key);
bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder));
bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder)));
if (bytes(value).length == 0 && keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){
// Avatar default
string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));
emit TextChanged(orderHash, key, avatarRecordValue);
emit TextChanged(hexHash, key, avatarRecordValue);
} else {
emit TextChanged(orderHash, key, value);
emit TextChanged(hexHash, key, value);
}
TextKeyMapping[rescueOrder][key] = value;
}
/**
* @dev Get the "content hash" of a given subdomain.
* EIP1577 functionality
*/
function contenthash(bytes32 nodeID) public view returns (bytes memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
return ContentsMapping[rescueOrder];
}
/**
* @dev Update the "content hash" of a given subdomain.
* EIP1577 functionality
*/
function setContenthash(bytes32 nodeID, bytes calldata hash) public {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
setContenthash(rescueOrder, hash);
}
/**
* @dev Update the "content hash" of a given MoonCat's subdomains.
*/
function setContenthash(uint256 rescueOrder, bytes calldata hash) public onlyMoonCatOwner(rescueOrder) {
emit ContenthashChanged(getSubdomainNameHash(uint2str(rescueOrder)), hash);
emit ContenthashChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), hash);
ContentsMapping[rescueOrder] = hash;
}
/**
* @dev Set the TTL for a given MoonCat's subdomains.
*/
function setTTL(uint rescueOrder, uint64 newTTL) public onlyMoonCatOwner(rescueOrder) {
IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
registry.setTTL(getSubdomainNameHash(uint2str(rescueOrder)), newTTL);
registry.setTTL(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), newTTL);
}
/**
* @dev Allow calling multiple functions on this contract in one transaction.
*/
function multicall(bytes[] calldata data) external returns(bytes[] memory results) {
results = new bytes[](data.length);
for (uint i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
require(success);
results[i] = result;
}
return results;
}
/**
* @dev Reverse lookup for ENS Node ID, to determine the MoonCat rescue order of the MoonCat associated with it.
*/
function getRescueOrderFromNodeId(bytes32 nodeID) public view returns (uint256) {
uint256 rescueOrder = NamehashMapping[nodeID];
if (rescueOrder == 0) {
// Are we actually dealing with MoonCat #0?
require(
nodeID == 0x8bde039a2a7841d31e0561fad9d5cfdfd4394902507c72856cf5950eaf9e7d5a // 0.ismymooncat.eth
|| nodeID == 0x1002474938c26fb23080c33c3db026c584b30ec6e7d3edf4717f3e01e627da26, // 0x00d658d50b.ismymooncat.eth
"Unknown Node ID"
);
}
return rescueOrder;
}
/**
* @dev Calculate the "namehash" of a specific domain, using the ENS standard algorithm.
* The namehash of 'ismymooncat.eth' is 0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15
* The namehash of 'foo.ismymooncat.eth' is keccak256(0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15, keccak256('foo'))
*/
function getSubdomainNameHash(string memory subdomain) public view returns (bytes32) {
return keccak256(abi.encodePacked(rootHash, keccak256(abi.encodePacked(subdomain))));
}
/**
* @dev Cache a single MoonCat's (identified by Rescue Order) subdomain hashes.
*/
function mapMoonCat(uint256 rescueOrder) public {
string memory orderSubdomain = uint2str(rescueOrder);
string memory hexSubdomain = bytes5ToHexString(MCR.rescueOrder(rescueOrder));
bytes32 orderHash = getSubdomainNameHash(orderSubdomain);
bytes32 hexHash = getSubdomainNameHash(hexSubdomain);
if (uint256(NamehashMapping[orderHash]) != 0) {
// Already Mapped
return;
}
NamehashMapping[orderHash] = rescueOrder;
NamehashMapping[hexHash] = rescueOrder;
if(MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) {
// MoonCat is not Acclimated
return;
}
IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
registry.setSubnodeRecord(rootHash, keccak256(bytes(orderSubdomain)), address(this), address(this), defaultTTL);
registry.setSubnodeRecord(rootHash, keccak256(bytes(hexSubdomain)), address(this), address(this), defaultTTL);
address moonCatOwner = MCA.ownerOf(rescueOrder);
lastAnnouncedAddress[rescueOrder] = moonCatOwner;
emit AddrChanged(orderHash, moonCatOwner);
emit AddrChanged(hexHash, moonCatOwner);
emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner));
emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner));
string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));
emit TextChanged(orderHash, "avatar", avatarRecordValue);
emit TextChanged(hexHash, "avatar", avatarRecordValue);
}
/**
* @dev Announce a single MoonCat's (identified by Rescue Order) assigned address.
*/
function announceMoonCat(uint256 rescueOrder) public {
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated");
address moonCatOwner = MCA.ownerOf(rescueOrder);
lastAnnouncedAddress[rescueOrder] = moonCatOwner;
bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder));
bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder)));
emit AddrChanged(orderHash, moonCatOwner);
emit AddrChanged(hexHash, moonCatOwner);
emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner));
emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner));
}
/**
* @dev Has an AddrChanged event been emitted for the current owner of a MoonCat (identified by Rescue Order)?
*/
function needsAnnouncing(uint256 rescueOrder) public view returns (bool) {
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated");
return lastAnnouncedAddress[rescueOrder] != MCA.ownerOf(rescueOrder);
}
/**
* @dev Convenience function to iterate through all MoonCats owned by an address to check if they need announcing.
*/
function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) {
uint256 balance = MCA.balanceOf(moonCatOwner);
uint256 announceCount = 0;
uint256[] memory tempRescueOrders = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);
if (lastAnnouncedAddress[rescueOrder] != moonCatOwner){
tempRescueOrders[announceCount] = rescueOrder;
announceCount++;
}
}
uint256[] memory rescueOrders = new uint256[](announceCount);
for (uint256 i = 0; i < announceCount; i++){
rescueOrders[i] = tempRescueOrders[i];
}
return rescueOrders;
}
/**
* @dev Convenience function to iterate through all MoonCats owned by sender to check if they need announcing.
*/
function needsAnnouncing() public view returns (uint256[] memory) {
return needsAnnouncing(msg.sender);
}
/**
* @dev Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes.
*/
function mapMoonCats(uint256[] memory rescueOrders) public {
for (uint256 i = 0; i < rescueOrders.length; i++) {
address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]];
if (lastAnnounced == address(0)){
mapMoonCat(rescueOrders[i]);
} else if (lastAnnounced != MCA.ownerOf(rescueOrders[i])){
announceMoonCat(rescueOrders[i]);
}
}
}
/**
* @dev Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes.
*/
function mapMoonCats(address moonCatOwner) public {
for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) {
uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);
address lastAnnounced = lastAnnouncedAddress[rescueOrder];
if (lastAnnounced == address(0)){
mapMoonCat(rescueOrder);
} else if (lastAnnounced != moonCatOwner){
announceMoonCat(rescueOrder);
}
}
}
/**
* @dev Convenience function to iterate through all MoonCats owned by the sender and announce or cache their subdomain hashes.
*/
function mapMoonCats() public {
mapMoonCats(msg.sender);
}
/**
* @dev Utility function to convert a bytes5 variable into a hexadecimal string.
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
*/
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function bytes5ToHexString(bytes5 x) internal pure returns (string memory) {
uint256 length = 5;
uint256 value = uint256(uint40(x));
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);
}
/**
* @dev Utility function to convert a uint256 variable into a decimal string.
*/
function uint2str(uint value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
} | Convenience function to iterate through all MoonCats owned by an address to check if they need announcing./ | function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) {
uint256 balance = MCA.balanceOf(moonCatOwner);
uint256 announceCount = 0;
uint256[] memory tempRescueOrders = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);
if (lastAnnouncedAddress[rescueOrder] != moonCatOwner){
tempRescueOrders[announceCount] = rescueOrder;
announceCount++;
}
}
uint256[] memory rescueOrders = new uint256[](announceCount);
for (uint256 i = 0; i < announceCount; i++){
rescueOrders[i] = tempRescueOrders[i];
}
return rescueOrders;
}
| 15,333,108 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract OwnerHelper
{
address public owner;
address public manager;
event ChangeOwner(address indexed _from, address indexed _to);
event ChangeManager(address indexed _from, address indexed _to);
modifier onlyOwner
{
require(msg.sender == owner, "ERROR: Not owner");
_;
}
modifier onlyManager
{
require(msg.sender == manager, "ERROR: Not manager");
_;
}
constructor()
{
owner = msg.sender;
}
function transferOwnership(address _to) onlyOwner public
{
require(_to != owner);
require(_to != manager);
require(_to != address(0x0));
address from = owner;
owner = _to;
emit ChangeOwner(from, _to);
}
function transferManager(address _to) onlyOwner public
{
require(_to != owner);
require(_to != manager);
require(_to != address(0x0));
address from = manager;
manager = _to;
emit ChangeManager(from, _to);
}
}
abstract contract ERC20Interface
{
event Transfer( address indexed _from, address indexed _to, uint _value);
event Approval( address indexed _owner, address indexed _spender, uint _value);
function totalSupply() view virtual public returns (uint _supply);
function balanceOf( address _who ) virtual public view returns (uint _value);
function transfer( address _to, uint _value) virtual public returns (bool _success);
function approve( address _spender, uint _value ) virtual public returns (bool _success);
function allowance( address _owner, address _spender ) virtual public view returns (uint _allowance);
function transferFrom( address _from, address _to, uint _value) virtual public returns (bool _success);
}
contract ARTIC is ERC20Interface, OwnerHelper
{
string public name;
uint public decimals;
string public symbol;
uint constant private E18 = 1000000000000000000;
uint constant private month = 2592000;
// Total 100,000,000
uint constant public maxTotalSupply = 100000000 * E18;
// Sale 10,000,000 (10%)
uint constant public maxSaleSupply = 10000000 * E18;
// Marketing 25,000,000 (25%)
uint constant public maxMktSupply = 25000000 * E18;
// Development 12,000,000 (12%)
uint constant public maxDevSupply = 12000000 * E18;
// EcoSystem 20,000,000 (20%)
uint constant public maxEcoSupply = 20000000 * E18;
// Legal & Compliance 15,000,000 (15%)
uint constant public maxLegalComplianceSupply = 15000000 * E18;
// Team 5,000,000 (5%)
uint constant public maxTeamSupply = 5000000 * E18;
// Advisors 3,000,000 (3%)
uint constant public maxAdvisorSupply = 3000000 * E18;
// Reserve 10,000,000 (10%)
uint constant public maxReserveSupply = 10000000 * E18;
// Lock
uint constant public teamVestingSupply = 500000 * E18;
uint constant public teamVestingLockDate = 12 * month;
uint constant public teamVestingTime = 10;
uint constant public advisorVestingSupply = 750000 * E18;
uint constant public advisorVestingTime = 4;
uint public totalTokenSupply;
uint public tokenIssuedSale;
uint public tokenIssuedMkt;
uint public tokenIssuedDev;
uint public tokenIssuedEco;
uint public tokenIssuedLegalCompliance;
uint public tokenIssuedTeam;
uint public tokenIssuedAdv;
uint public tokenIssuedRsv;
uint public burnTokenSupply;
mapping (address => uint) public balances;
mapping (address => mapping ( address => uint )) public approvals;
mapping (uint => uint) public tmVestingTimer;
mapping (uint => uint) public tmVestingBalances;
mapping (uint => uint) public advVestingTimer;
mapping (uint => uint) public advVestingBalances;
bool public tokenLock = true;
bool public saleTime = true;
uint public endSaleTime = 0;
event SaleIssue(address indexed _to, uint _tokens);
event DevIssue(address indexed _to, uint _tokens);
event EcoIssue(address indexed _to, uint _tokens);
event LegalComplianceIssue(address indexed _to, uint _tokens);
event MktIssue(address indexed _to, uint _tokens);
event RsvIssue(address indexed _to, uint _tokens);
event TeamIssue(address indexed _to, uint _tokens);
event AdvIssue(address indexed _to, uint _tokens);
event Burn(address indexed _from, uint _tokens);
event TokenUnlock(address indexed _to, uint _tokens);
event EndSale(uint _date);
constructor()
{
name = "ARTIC";
decimals = 18;
symbol = "ARTIC";
totalTokenSupply = maxTotalSupply;
balances[owner] = totalTokenSupply;
tokenIssuedSale = 0;
tokenIssuedDev = 0;
tokenIssuedEco = 0;
tokenIssuedLegalCompliance = 0;
tokenIssuedMkt = 0;
tokenIssuedRsv = 0;
tokenIssuedTeam = 0;
tokenIssuedAdv = 0;
burnTokenSupply = 0;
require(maxTeamSupply == teamVestingSupply * teamVestingTime, "ERROR: MaxTeamSupply");
require(maxAdvisorSupply == advisorVestingSupply * advisorVestingTime, "ERROR: MaxAdvisorSupply");
require(maxTotalSupply == maxSaleSupply + maxDevSupply + maxEcoSupply + maxMktSupply + maxReserveSupply + maxTeamSupply + maxAdvisorSupply + maxLegalComplianceSupply, "ERROR: MaxTotalSupply");
}
function totalSupply() view override public returns (uint)
{
return totalTokenSupply;
}
function balanceOf(address _who) view override public returns (uint)
{
return balances[_who];
}
function transfer(address _to, uint _value) override public returns (bool)
{
require(isTransferable() == true);
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint _value) override public returns (bool)
{
require(isTransferable() == true);
require(balances[msg.sender] >= _value);
approvals[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view override public returns (uint)
{
return approvals[_owner][_spender];
}
function transferFrom(address _from, address _to, uint _value) override public returns (bool)
{
require(isTransferable() == true);
require(balances[_from] >= _value);
require(approvals[_from][msg.sender] >= _value);
approvals[_from][msg.sender] = approvals[_from][msg.sender] - _value;
balances[_from] = balances[_from] - _value;
balances[_to] = balances[_to] + _value;
emit Transfer(_from, _to, _value);
return true;
}
function saleIssue(address _to) onlyOwner public
{
require(tokenIssuedSale == 0);
uint tokens = maxSaleSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedSale = tokenIssuedSale + tokens;
emit SaleIssue(_to, tokens);
}
function devIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedDev == 0);
uint tokens = maxDevSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedDev = tokenIssuedDev + tokens;
emit DevIssue(_to, tokens);
}
function ecoIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedEco == 0);
uint tokens = maxEcoSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedEco = tokenIssuedEco + tokens;
emit EcoIssue(_to, tokens);
}
function mktIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedMkt == 0);
uint tokens = maxMktSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedMkt = tokenIssuedMkt + tokens;
emit MktIssue(_to, tokens);
}
function legalComplianceIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedLegalCompliance == 0);
uint tokens = maxLegalComplianceSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedLegalCompliance = tokenIssuedLegalCompliance + tokens;
emit LegalComplianceIssue(_to, tokens);
}
function rsvIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedRsv == 0);
uint tokens = maxReserveSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedRsv = tokenIssuedRsv + tokens;
emit RsvIssue(_to, tokens);
}
function teamIssue(address _to, uint _time /* 몇 번째 지급인지 */) onlyOwner public
{
require(saleTime == false);
require( _time < teamVestingTime);
uint nowTime = block.timestamp;
require( nowTime > tmVestingTimer[_time] );
uint tokens = teamVestingSupply;
require(tokens == tmVestingBalances[_time]);
require(maxTeamSupply >= tokenIssuedTeam + tokens);
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tmVestingBalances[_time] = 0;
tokenIssuedTeam = tokenIssuedTeam + tokens;
emit TeamIssue(_to, tokens);
}
function advisorIssue(address _to, uint _time) onlyOwner public
{
require(saleTime == false);
require( _time < advisorVestingTime);
uint nowTime = block.timestamp;
require( nowTime > advVestingTimer[_time] );
uint tokens = advisorVestingSupply;
require(tokens == advVestingBalances[_time]);
require(maxAdvisorSupply >= tokenIssuedAdv + tokens);
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
advVestingBalances[_time] = 0;
tokenIssuedAdv = tokenIssuedAdv + tokens;
emit AdvIssue(_to, tokens);
}
function isTransferable() private view returns (bool)
{
if(tokenLock == false)
{
return true;
}
else if(msg.sender == owner)
{
return true;
}
return false;
}
function setTokenUnlock() onlyManager public
{
require(tokenLock == true);
require(saleTime == false);
tokenLock = false;
}
function setTokenLock() onlyManager public
{
require(tokenLock == false);
tokenLock = true;
}
function endSale() onlyOwner public
{
require(saleTime == true);
require(maxSaleSupply == tokenIssuedSale);
saleTime = false;
uint nowTime = block.timestamp;
endSaleTime = nowTime;
for(uint i = 0; i < teamVestingTime; i++)
{
tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month);
tmVestingBalances[i] = teamVestingSupply;
}
for(uint i = 0; i < advisorVestingTime; i++)
{
advVestingTimer[i] = endSaleTime + (3 * i * month);
advVestingBalances[i] = advisorVestingSupply;
}
emit EndSale(endSaleTime);
}
function burnToken(uint _value) onlyManager public
{
uint tokens = _value * E18;
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender] - tokens;
burnTokenSupply = burnTokenSupply + tokens;
totalTokenSupply = totalTokenSupply - tokens;
emit Burn(msg.sender, tokens);
}
function close() onlyOwner public
{
selfdestruct(payable(msg.sender));
}
} | Total 100,000,000 Sale 10,000,000 (10%) Marketing 25,000,000 (25%) Development 12,000,000 (12%) EcoSystem 20,000,000 (20%) Legal & Compliance 15,000,000 (15%) Team 5,000,000 (5%) Advisors 3,000,000 (3%) Reserve 10,000,000 (10%) Lock | {
string public name;
uint public decimals;
string public symbol;
uint constant private E18 = 1000000000000000000;
uint constant private month = 2592000;
uint constant public maxTotalSupply = 100000000 * E18;
uint constant public maxSaleSupply = 10000000 * E18;
uint constant public maxMktSupply = 25000000 * E18;
uint constant public maxDevSupply = 12000000 * E18;
uint constant public maxEcoSupply = 20000000 * E18;
uint constant public maxLegalComplianceSupply = 15000000 * E18;
uint constant public maxTeamSupply = 5000000 * E18;
uint constant public maxAdvisorSupply = 3000000 * E18;
uint constant public maxReserveSupply = 10000000 * E18;
uint constant public teamVestingSupply = 500000 * E18;
uint constant public teamVestingLockDate = 12 * month;
uint constant public teamVestingTime = 10;
uint constant public advisorVestingSupply = 750000 * E18;
uint constant public advisorVestingTime = 4;
uint public totalTokenSupply;
uint public tokenIssuedSale;
uint public tokenIssuedMkt;
uint public tokenIssuedDev;
uint public tokenIssuedEco;
uint public tokenIssuedLegalCompliance;
uint public tokenIssuedTeam;
uint public tokenIssuedAdv;
uint public tokenIssuedRsv;
uint public burnTokenSupply;
mapping (address => uint) public balances;
mapping (address => mapping ( address => uint )) public approvals;
mapping (uint => uint) public tmVestingTimer;
mapping (uint => uint) public tmVestingBalances;
mapping (uint => uint) public advVestingTimer;
mapping (uint => uint) public advVestingBalances;
bool public tokenLock = true;
bool public saleTime = true;
uint public endSaleTime = 0;
event SaleIssue(address indexed _to, uint _tokens);
event DevIssue(address indexed _to, uint _tokens);
event EcoIssue(address indexed _to, uint _tokens);
event LegalComplianceIssue(address indexed _to, uint _tokens);
event MktIssue(address indexed _to, uint _tokens);
event RsvIssue(address indexed _to, uint _tokens);
event TeamIssue(address indexed _to, uint _tokens);
event AdvIssue(address indexed _to, uint _tokens);
event Burn(address indexed _from, uint _tokens);
event TokenUnlock(address indexed _to, uint _tokens);
event EndSale(uint _date);
constructor()
{
name = "ARTIC";
decimals = 18;
symbol = "ARTIC";
totalTokenSupply = maxTotalSupply;
balances[owner] = totalTokenSupply;
tokenIssuedSale = 0;
tokenIssuedDev = 0;
tokenIssuedEco = 0;
tokenIssuedLegalCompliance = 0;
tokenIssuedMkt = 0;
tokenIssuedRsv = 0;
tokenIssuedTeam = 0;
tokenIssuedAdv = 0;
burnTokenSupply = 0;
require(maxTeamSupply == teamVestingSupply * teamVestingTime, "ERROR: MaxTeamSupply");
require(maxAdvisorSupply == advisorVestingSupply * advisorVestingTime, "ERROR: MaxAdvisorSupply");
require(maxTotalSupply == maxSaleSupply + maxDevSupply + maxEcoSupply + maxMktSupply + maxReserveSupply + maxTeamSupply + maxAdvisorSupply + maxLegalComplianceSupply, "ERROR: MaxTotalSupply");
}
function totalSupply() view override public returns (uint)
{
return totalTokenSupply;
}
function balanceOf(address _who) view override public returns (uint)
{
return balances[_who];
}
function transfer(address _to, uint _value) override public returns (bool)
{
require(isTransferable() == true);
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint _value) override public returns (bool)
{
require(isTransferable() == true);
require(balances[msg.sender] >= _value);
approvals[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view override public returns (uint)
{
return approvals[_owner][_spender];
}
function transferFrom(address _from, address _to, uint _value) override public returns (bool)
{
require(isTransferable() == true);
require(balances[_from] >= _value);
require(approvals[_from][msg.sender] >= _value);
approvals[_from][msg.sender] = approvals[_from][msg.sender] - _value;
balances[_from] = balances[_from] - _value;
balances[_to] = balances[_to] + _value;
emit Transfer(_from, _to, _value);
return true;
}
function saleIssue(address _to) onlyOwner public
{
require(tokenIssuedSale == 0);
uint tokens = maxSaleSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedSale = tokenIssuedSale + tokens;
emit SaleIssue(_to, tokens);
}
function devIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedDev == 0);
uint tokens = maxDevSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedDev = tokenIssuedDev + tokens;
emit DevIssue(_to, tokens);
}
function ecoIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedEco == 0);
uint tokens = maxEcoSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedEco = tokenIssuedEco + tokens;
emit EcoIssue(_to, tokens);
}
function mktIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedMkt == 0);
uint tokens = maxMktSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedMkt = tokenIssuedMkt + tokens;
emit MktIssue(_to, tokens);
}
function legalComplianceIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedLegalCompliance == 0);
uint tokens = maxLegalComplianceSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedLegalCompliance = tokenIssuedLegalCompliance + tokens;
emit LegalComplianceIssue(_to, tokens);
}
function rsvIssue(address _to) onlyOwner public
{
require(saleTime == false);
require(tokenIssuedRsv == 0);
uint tokens = maxReserveSupply;
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tokenIssuedRsv = tokenIssuedRsv + tokens;
emit RsvIssue(_to, tokens);
}
function teamIssue(address _to, uint _time /* 몇 번째 지급인지 */) onlyOwner public
{
require(saleTime == false);
require( _time < teamVestingTime);
uint nowTime = block.timestamp;
require( nowTime > tmVestingTimer[_time] );
uint tokens = teamVestingSupply;
require(tokens == tmVestingBalances[_time]);
require(maxTeamSupply >= tokenIssuedTeam + tokens);
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
tmVestingBalances[_time] = 0;
tokenIssuedTeam = tokenIssuedTeam + tokens;
emit TeamIssue(_to, tokens);
}
function advisorIssue(address _to, uint _time) onlyOwner public
{
require(saleTime == false);
require( _time < advisorVestingTime);
uint nowTime = block.timestamp;
require( nowTime > advVestingTimer[_time] );
uint tokens = advisorVestingSupply;
require(tokens == advVestingBalances[_time]);
require(maxAdvisorSupply >= tokenIssuedAdv + tokens);
balances[msg.sender] = balances[msg.sender] - tokens;
balances[_to] = balances[_to] + tokens;
advVestingBalances[_time] = 0;
tokenIssuedAdv = tokenIssuedAdv + tokens;
emit AdvIssue(_to, tokens);
}
function isTransferable() private view returns (bool)
{
if(tokenLock == false)
{
return true;
}
else if(msg.sender == owner)
{
return true;
}
return false;
}
function isTransferable() private view returns (bool)
{
if(tokenLock == false)
{
return true;
}
else if(msg.sender == owner)
{
return true;
}
return false;
}
function isTransferable() private view returns (bool)
{
if(tokenLock == false)
{
return true;
}
else if(msg.sender == owner)
{
return true;
}
return false;
}
function setTokenUnlock() onlyManager public
{
require(tokenLock == true);
require(saleTime == false);
tokenLock = false;
}
function setTokenLock() onlyManager public
{
require(tokenLock == false);
tokenLock = true;
}
function endSale() onlyOwner public
{
require(saleTime == true);
require(maxSaleSupply == tokenIssuedSale);
saleTime = false;
uint nowTime = block.timestamp;
endSaleTime = nowTime;
for(uint i = 0; i < teamVestingTime; i++)
{
tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month);
tmVestingBalances[i] = teamVestingSupply;
}
for(uint i = 0; i < advisorVestingTime; i++)
{
advVestingTimer[i] = endSaleTime + (3 * i * month);
advVestingBalances[i] = advisorVestingSupply;
}
emit EndSale(endSaleTime);
}
function endSale() onlyOwner public
{
require(saleTime == true);
require(maxSaleSupply == tokenIssuedSale);
saleTime = false;
uint nowTime = block.timestamp;
endSaleTime = nowTime;
for(uint i = 0; i < teamVestingTime; i++)
{
tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month);
tmVestingBalances[i] = teamVestingSupply;
}
for(uint i = 0; i < advisorVestingTime; i++)
{
advVestingTimer[i] = endSaleTime + (3 * i * month);
advVestingBalances[i] = advisorVestingSupply;
}
emit EndSale(endSaleTime);
}
function endSale() onlyOwner public
{
require(saleTime == true);
require(maxSaleSupply == tokenIssuedSale);
saleTime = false;
uint nowTime = block.timestamp;
endSaleTime = nowTime;
for(uint i = 0; i < teamVestingTime; i++)
{
tmVestingTimer[i] = endSaleTime + teamVestingLockDate + (i * month);
tmVestingBalances[i] = teamVestingSupply;
}
for(uint i = 0; i < advisorVestingTime; i++)
{
advVestingTimer[i] = endSaleTime + (3 * i * month);
advVestingBalances[i] = advisorVestingSupply;
}
emit EndSale(endSaleTime);
}
function burnToken(uint _value) onlyManager public
{
uint tokens = _value * E18;
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender] - tokens;
burnTokenSupply = burnTokenSupply + tokens;
totalTokenSupply = totalTokenSupply - tokens;
emit Burn(msg.sender, tokens);
}
function close() onlyOwner public
{
selfdestruct(payable(msg.sender));
}
} | 10,245,440 |
./full_match/1/0xcbc0A8d5C7352Fe3625614ea343019e6d6b89031/sources/contracts/v2/templeLineOfCredit/TempleLineOfCredit.sol | Liquidation may be paused in order for users to recover/repay debt after emergency actions/ | function setLiquidationsPaused(bool isPaused) external override onlyElevatedAccess {
liquidationsPaused = isPaused;
emit LiquidationsPausedSet(isPaused);
}
| 5,002,823 |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
/**
* @dev Checks if msg.sender is in whitelist.
*/
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/**
* @title TAOCurrency
*/
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) {
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title TAO
*/
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
/**
* 0 = TAO
* 1 = Name
*/
uint8 public typeId;
/**
* @dev Constructor function
*/
constructor (string _name,
address _originId,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
/**
* @dev Checks if calling address is Vault contract
*/
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
/**
* @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
/**
* @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
/**
* @title Position
*/
contract Position is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 4;
uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4);
uint256 public totalSupply;
// Mapping from Name ID to bool value whether or not it has received Position Token
mapping (address => bool) public receivedToken;
// Mapping from Name ID to its total available balance
mapping (address => uint256) public balanceOf;
// Mapping from Name's TAO ID to its staked amount
mapping (address => mapping(address => uint256)) public taoStakedBalance;
// Mapping from TAO ID to its total staked amount
mapping (address => uint256) public totalTAOStakedBalance;
// This generates a public event on the blockchain that will notify clients
event Mint(address indexed nameId, uint256 value);
event Stake(address indexed nameId, address indexed taoId, uint256 value);
event Unstake(address indexed nameId, address indexed taoId, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId`
* @param _nameId Address to receive the tokens
* @return true on success
*/
function mintToken(address _nameId) public inWhitelist returns (bool) {
// Make sure _nameId has not received Position Token
require (receivedToken[_nameId] == false);
receivedToken[_nameId] = true;
balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME);
totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME);
emit Mint(_nameId, MAX_SUPPLY_PER_NAME);
return true;
}
/**
* @dev Get staked balance of `_nameId`
* @param _nameId The Name ID to be queried
* @return total staked balance
*/
function stakedBalance(address _nameId) public view returns (uint256) {
return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]);
}
/**
* @dev Stake `_value` tokens on `_taoId` from `_nameId`
* @param _nameId The Name ID that wants to stake
* @param _taoId The TAO ID to stake
* @param _value The amount to stake
* @return true on success
*/
function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough
balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value);
emit Stake(_nameId, _taoId, _value);
return true;
}
/**
* @dev Unstake `_value` tokens from `_nameId`'s `_taoId`
* @param _nameId The Name ID that wants to unstake
* @param _taoId The TAO ID to unstake
* @param _value The amount to unstake
* @return true on success
*/
function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough
require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value);
balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance
emit Unstake(_nameId, _taoId, _value);
return true;
}
}
/**
* @title NameTAOLookup
*
*/
contract NameTAOLookup is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
struct NameTAOInfo {
string name;
address nameTAOAddress;
string parentName;
uint256 typeId; // 0 = TAO. 1 = Name
}
uint256 public internalId;
uint256 public totalNames;
uint256 public totalTAOs;
mapping (uint256 => NameTAOInfo) internal nameTAOInfos;
mapping (bytes32 => uint256) internal internalIdLookup;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a name exist in the list
* @param _name The name to be checked
* @return true if yes, false otherwise
*/
function isExist(string _name) public view returns (bool) {
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
return (internalIdLookup[_nameKey] > 0);
}
/**
* @dev Add a new NameTAOInfo
* @param _name The name of the Name/TAO
* @param _nameTAOAddress The address of the Name/TAO
* @param _parentName The parent name of the Name/TAO
* @param _typeId If TAO = 0. Name = 1
* @return true on success
*/
function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) {
require (bytes(_name).length > 0);
require (_nameTAOAddress != address(0));
require (bytes(_parentName).length > 0);
require (_typeId == 0 || _typeId == 1);
require (!isExist(_name));
internalId++;
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
internalIdLookup[_nameKey] = internalId;
NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId];
_nameTAOInfo.name = _name;
_nameTAOInfo.nameTAOAddress = _nameTAOAddress;
_nameTAOInfo.parentName = _parentName;
_nameTAOInfo.typeId = _typeId;
if (_typeId == 0) {
totalTAOs++;
} else {
totalNames++;
}
return true;
}
/**
* @dev Get the NameTAOInfo given a name
* @param _name The name to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByName(string _name) public view returns (string, address, string, uint256) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Get the NameTAOInfo given an ID
* @param _internalId The internal ID to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) {
require (nameTAOInfos[_internalId].nameTAOAddress != address(0));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Return the nameTAOAddress given a _name
* @param _name The name to be queried
* @return the nameTAOAddress of the name
*/
function getAddressByName(string _name) public view returns (address) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return _nameTAOInfo.nameTAOAddress;
}
}
/**
* @title NamePublicKey
*/
contract NamePublicKey {
using SafeMath for uint256;
address public nameFactoryAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
struct PublicKey {
bool created;
address defaultKey;
address[] keys;
}
// Mapping from nameId to its PublicKey
mapping (address => PublicKey) internal publicKeys;
// Event to be broadcasted to public when a publicKey is added to a Name
event AddKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is removed from a Name
event RemoveKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is set as default for a Name
event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress);
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name ID exist in the list of Public Keys
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return publicKeys[_id].created;
}
/**
* @dev Store the PublicKey info for a Name
* @param _id The ID of the Name
* @param _defaultKey The default public key for this Name
* @return true on success
*/
function add(address _id, address _defaultKey)
public
isName(_id)
onlyFactory returns (bool) {
require (!isExist(_id));
require (_defaultKey != address(0));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.created = true;
_publicKey.defaultKey = _defaultKey;
_publicKey.keys.push(_defaultKey);
return true;
}
/**
* @dev Get total publicKeys count for a Name
* @param _id The ID of the Name
* @return total publicKeys count
*/
function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) {
require (isExist(_id));
return publicKeys[_id].keys.length;
}
/**
* @dev Check whether or not a publicKey exist in the list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to check
* @return true if yes. false otherwise
*/
function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) {
require (isExist(_id));
require (_key != address(0));
PublicKey memory _publicKey = publicKeys[_id];
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
return true;
}
}
return false;
}
/**
* @dev Add publicKey to list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to be added
*/
function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (!isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.keys.push(_key);
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit AddKey(_id, _key, _nonce);
}
/**
* @dev Get default public key of a Name
* @param _id The ID of the Name
* @return the default public key
*/
function getDefaultKey(address _id) public isName(_id) view returns (address) {
require (isExist(_id));
return publicKeys[_id].defaultKey;
}
/**
* @dev Get list of publicKeys of a Name
* @param _id The ID of the Name
* @param _from The starting index
* @param _to The ending index
* @return list of publicKeys
*/
function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) {
require (isExist(_id));
require (_from >= 0 && _to >= _from);
PublicKey memory _publicKey = publicKeys[_id];
require (_publicKey.keys.length > 0);
address[] memory _keys = new address[](_to.sub(_from).add(1));
if (_to > _publicKey.keys.length.sub(1)) {
_to = _publicKey.keys.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_keys[i.sub(_from)] = _publicKey.keys[i];
}
return _keys;
}
/**
* @dev Remove publicKey from the list
* @param _id The ID of the Name
* @param _key The publicKey to be removed
*/
function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
// Can't remove default key
require (_key != _publicKey.defaultKey);
require (_publicKey.keys.length > 1);
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
delete _publicKey.keys[i];
_publicKey.keys.length--;
uint256 _nonce = _nameFactory.incrementNonce(_id);
break;
}
}
require (_nonce > 0);
emit RemoveKey(_id, _key, _nonce);
}
/**
* @dev Set a publicKey as the default for a Name
* @param _id The ID of the Name
* @param _defaultKey The defaultKey to be set
* @param _signatureV The V part of the signature for this update
* @param _signatureR The R part of the signature for this update
* @param _signatureS The S part of the signature for this update
*/
function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _defaultKey));
bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey));
require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.defaultKey = _defaultKey;
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit SetDefaultKey(_id, _defaultKey, _nonce);
}
}
/**
* @title NameFactory
*
* The purpose of this contract is to allow node to create Name
*/
contract NameFactory is TheAO {
using SafeMath for uint256;
address public positionAddress;
address public nameTAOVaultAddress;
address public nameTAOLookupAddress;
address public namePublicKeyAddress;
Position internal _position;
NameTAOLookup internal _nameTAOLookup;
NameTAOPosition internal _nameTAOPosition;
NamePublicKey internal _namePublicKey;
address[] internal names;
// Mapping from eth address to Name ID
mapping (address => address) public ethAddressToNameId;
// Mapping from Name ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when a Name is created
event CreateName(address indexed ethAddress, address nameId, uint256 index, string name);
/**
* @dev Constructor function
*/
constructor(address _positionAddress, address _nameTAOVaultAddress) public {
positionAddress = _positionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_position = Position(positionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update Name's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the NameTAOLookup Address
* @param _nameTAOLookupAddress The address of NameTAOLookup
*/
function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO {
require (_nameTAOLookupAddress != address(0));
nameTAOLookupAddress = _nameTAOLookupAddress;
_nameTAOLookup = NameTAOLookup(nameTAOLookupAddress);
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(nameTAOPositionAddress);
}
/**
* @dev The AO set the NamePublicKey Address
* @param _namePublicKeyAddress The address of NamePublicKey
*/
function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO {
require (_namePublicKeyAddress != address(0));
namePublicKeyAddress = _namePublicKeyAddress;
_namePublicKey = NamePublicKey(namePublicKeyAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a Name
* @param _nameId The ID of the Name
* @return current nonce
*/
function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) {
// Check if _nameId exist
require (nonces[_nameId] > 0);
nonces[_nameId]++;
return nonces[_nameId];
}
/**
* @dev Create a Name
* @param _name The name of the Name
* @param _datHash The datHash to this Name's profile
* @param _database The database for this Name
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this Name
*/
function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
// Only one Name per ETH address
require (ethAddressToNameId[msg.sender] == address(0));
// The address is the Name ID (which is also a TAO ID)
address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[nameId]++;
ethAddressToNameId[msg.sender] = nameId;
// Store the name lookup information
require (_nameTAOLookup.add(_name, nameId, 'human', 1));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(nameId, nameId, nameId, nameId));
// Store the public key information
require (_namePublicKey.add(nameId, msg.sender));
names.push(nameId);
// Need to mint Position token for this Name
require (_position.mintToken(nameId));
emit CreateName(msg.sender, nameId, names.length.sub(1), _name);
}
/**
* @dev Get Name information
* @param _nameId The ID of the Name to be queried
* @return The name of the Name
* @return The originId of the Name (in this case, it's the creator node's ETH address)
* @return The datHash of the Name
* @return The database of the Name
* @return The keyValue of the Name
* @return The contentId of the Name
* @return The typeId of the Name
*/
function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) {
Name _name = Name(_nameId);
return (
_name.name(),
_name.originId(),
_name.datHash(),
_name.database(),
_name.keyValue(),
_name.contentId(),
_name.typeId()
);
}
/**
* @dev Get total Names count
* @return total Names count
*/
function getTotalNamesCount() public view returns (uint256) {
return names.length;
}
/**
* @dev Get list of Name IDs
* @param _from The starting index
* @param _to The ending index
* @return list of Name IDs
*/
function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from);
require (names.length > 0);
address[] memory _names = new address[](_to.sub(_from).add(1));
if (_to > names.length.sub(1)) {
_to = names.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_names[i.sub(_from)] = names[i];
}
return _names;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be Name's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The name of the Name
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
*/
function validateNameSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public view returns (bool) {
require (_nameTAOLookup.isExist(_name));
address _nameId = _nameTAOLookup.getAddressByName(_name);
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_validateAddress != address(0)) {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _validateAddress &&
_namePublicKey.isKeyExist(_nameId, _validateAddress)
);
} else {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _namePublicKey.getDefaultKey(_nameId)
);
}
}
}
/**
* @title AOStringSetting
*
* This contract stores all AO string setting variables
*/
contract AOStringSetting is TheAO {
// Mapping from settingId to it's actual string value
mapping (uint256 => string) public settingValue;
// Mapping from settingId to it's potential string value that is at pending state
mapping (uint256 => string) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The string value to be set
*/
function setPendingValue(uint256 _settingId, string _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
string memory _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBytesSetting
*
* This contract stores all AO bytes32 setting variables
*/
contract AOBytesSetting is TheAO {
// Mapping from settingId to it's actual bytes32 value
mapping (uint256 => bytes32) public settingValue;
// Mapping from settingId to it's potential bytes32 value that is at pending state
mapping (uint256 => bytes32) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bytes32 value to be set
*/
function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bytes32 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOAddressSetting
*
* This contract stores all AO address setting variables
*/
contract AOAddressSetting is TheAO {
// Mapping from settingId to it's actual address value
mapping (uint256 => address) public settingValue;
// Mapping from settingId to it's potential address value that is at pending state
mapping (uint256 => address) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The address value to be set
*/
function setPendingValue(uint256 _settingId, address _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
address _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBoolSetting
*
* This contract stores all AO bool setting variables
*/
contract AOBoolSetting is TheAO {
// Mapping from settingId to it's actual bool value
mapping (uint256 => bool) public settingValue;
// Mapping from settingId to it's potential bool value that is at pending state
mapping (uint256 => bool) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bool value to be set
*/
function setPendingValue(uint256 _settingId, bool _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bool _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOUintSetting
*
* This contract stores all AO uint256 setting variables
*/
contract AOUintSetting is TheAO {
// Mapping from settingId to it's actual uint256 value
mapping (uint256 => uint256) public settingValue;
// Mapping from settingId to it's potential uint256 value that is at pending state
mapping (uint256 => uint256) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The uint256 value to be set
*/
function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
uint256 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOSettingAttribute
*
* This contract stores all AO setting data/state
*/
contract AOSettingAttribute is TheAO {
NameTAOPosition internal _nameTAOPosition;
struct SettingData {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created the setting
address creatorTAOId; // The taoId that created the setting
address associatedTAOId; // The taoId that the setting affects
string settingName; // The human-readable name of the setting
/**
* 1 => uint256
* 2 => bool
* 3 => address
* 4 => bytes32
* 5 => string (catch all)
*/
uint8 settingType;
bool pendingCreate; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
string settingDataJSON; // Catch-all
}
struct SettingState {
uint256 settingId; // Identifier of this setting
bool pendingUpdate; // State when setting is in process of being updated
address updateAdvocateNameId; // The nameId of the Advocate that performed the update
/**
* A child of the associatedTAOId with the update Logos.
* This tells the setting contract that there is a proposal TAO that is a Child TAO
* of the associated TAO, which will be responsible for deciding if the update to the
* setting is accepted or rejected.
*/
address proposalTAOId;
/**
* Signature of the proposalTAOId and update value by the associatedTAOId
* Advocate's Name's address.
*/
string updateSignature;
/**
* The proposalTAOId moves here when setting value changes successfully
*/
address lastUpdateTAOId;
string settingStateJSON; // Catch-all
}
struct SettingDeprecation {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created this deprecation
address creatorTAOId; // The taoId that created this deprecation
address associatedTAOId; // The taoId that the setting affects
bool pendingDeprecated; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
bool migrated; // State when this setting is fully migrated
// holds the pending new settingId value when a deprecation is set
uint256 pendingNewSettingId;
// holds the new settingId that has been approved by associatedTAOId
uint256 newSettingId;
// holds the pending new contract address for this setting
address pendingNewSettingContractAddress;
// holds the new contract address for this setting
address newSettingContractAddress;
}
struct AssociatedTAOSetting {
bytes32 associatedTAOSettingId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSetting {
bytes32 creatorTAOSettingId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
struct AssociatedTAOSettingDeprecation {
bytes32 associatedTAOSettingDeprecationId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSettingDeprecation {
bytes32 creatorTAOSettingDeprecationId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
// Mapping from settingId to it's data
mapping (uint256 => SettingData) internal settingDatas;
// Mapping from settingId to it's state
mapping (uint256 => SettingState) internal settingStates;
// Mapping from settingId to it's deprecation info
mapping (uint256 => SettingDeprecation) internal settingDeprecations;
// Mapping from associatedTAOSettingId to AssociatedTAOSetting
mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings;
// Mapping from creatorTAOSettingId to CreatorTAOSetting
mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings;
// Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation
mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations;
// Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation
mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations;
/**
* @dev Constructor function
*/
constructor(address _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Add setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return The ID of the "Associated" setting
* @return The ID of the "Creator" setting
*/
function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) {
// Store setting data/state
require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData));
// Store the associatedTAOSetting info
bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
_associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId;
_associatedTAOSetting.associatedTAOId = _associatedTAOId;
_associatedTAOSetting.settingId = _settingId;
// Store the creatorTAOSetting info
bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
_creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId;
_creatorTAOSetting.creatorTAOId = _creatorTAOId;
_creatorTAOSetting.settingId = _settingId;
return (_associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Get Setting Data of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) {
SettingData memory _settingData = settingDatas[_settingId];
return (
_settingData.settingId,
_settingData.creatorNameId,
_settingData.creatorTAOId,
_settingData.associatedTAOId,
_settingData.settingName,
_settingData.settingType,
_settingData.pendingCreate,
_settingData.locked,
_settingData.rejected,
_settingData.settingDataJSON
);
}
/**
* @dev Get Associated TAO Setting info
* @param _associatedTAOSettingId The ID of the associated tao setting
*/
function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) {
AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
return (
_associatedTAOSetting.associatedTAOSettingId,
_associatedTAOSetting.associatedTAOId,
_associatedTAOSetting.settingId
);
}
/**
* @dev Get Creator TAO Setting info
* @param _creatorTAOSettingId The ID of the creator tao setting
*/
function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) {
CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
return (
_creatorTAOSetting.creatorTAOSettingId,
_creatorTAOSetting.creatorTAOId,
_creatorTAOSetting.settingId
);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingData.locked = false;
} else {
// Reject the setting
_settingData.pendingCreate = false;
_settingData.rejected = true;
}
return true;
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == false &&
_settingData.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId)
);
// Update the setting data
_settingData.pendingCreate = false;
_settingData.locked = true;
return true;
}
/**
* @dev Store setting update data
* @param _settingId The ID of the setting to be updated
* @param _settingType The type of this setting
* @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData memory _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.settingType == _settingType &&
_settingData.pendingCreate == false &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) &&
bytes(_updateSignature).length > 0
);
// Make sure setting is not in the middle of updating
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.pendingUpdate == false);
// Make sure setting is not yet deprecated
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
if (_settingDeprecation.settingId == _settingId) {
require (_settingDeprecation.migrated == false);
}
// Store the SettingState data
_settingState.pendingUpdate = true;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
_settingState.proposalTAOId = _proposalTAOId;
_settingState.updateSignature = _updateSignature;
_settingState.settingStateJSON = _extraData;
return true;
}
/**
* @dev Get setting state
* @param _settingId The ID of the setting
*/
function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) {
SettingState memory _settingState = settingStates[_settingId];
return (
_settingState.settingId,
_settingState.pendingUpdate,
_settingState.updateAdvocateNameId,
_settingState.proposalTAOId,
_settingState.updateSignature,
_settingState.lastUpdateTAOId,
_settingState.settingStateJSON
);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _proposalTAOAdvocate The advocate of the proposal TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId &&
_settingState.pendingUpdate == true &&
_proposalTAOAdvocate != address(0) &&
_proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of associatedTAOId can finalize the update
_settingData.locked = false;
} else {
// Set pendingUpdate to false
_settingState.pendingUpdate = false;
_settingState.proposalTAOId = address(0);
}
return true;
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @return true on success
*/
function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == false &&
_settingData.locked == false &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0));
// Update the setting data
_settingData.locked = true;
// Update the setting state
_settingState.pendingUpdate = false;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
address _proposalTAOId = _settingState.proposalTAOId;
_settingState.proposalTAOId = address(0);
_settingState.lastUpdateTAOId = _proposalTAOId;
return true;
}
/**
* @dev Add setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return The ID of the "Associated" setting deprecation
* @return The ID of the "Creator" setting deprecation
*/
function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) {
require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress));
// Store the associatedTAOSettingDeprecation info
bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId;
_associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId;
_associatedTAOSettingDeprecation.settingId = _settingId;
// Store the creatorTAOSettingDeprecation info
bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId;
_creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId;
_creatorTAOSettingDeprecation.settingId = _settingId;
return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Get Setting Deprecation info of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) {
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
return (
_settingDeprecation.settingId,
_settingDeprecation.creatorNameId,
_settingDeprecation.creatorTAOId,
_settingDeprecation.associatedTAOId,
_settingDeprecation.pendingDeprecated,
_settingDeprecation.locked,
_settingDeprecation.rejected,
_settingDeprecation.migrated,
_settingDeprecation.pendingNewSettingId,
_settingDeprecation.newSettingId,
_settingDeprecation.pendingNewSettingContractAddress,
_settingDeprecation.newSettingContractAddress
);
}
/**
* @dev Get Associated TAO Setting Deprecation info
* @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation
*/
function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
return (
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId,
_associatedTAOSettingDeprecation.associatedTAOId,
_associatedTAOSettingDeprecation.settingId
);
}
/**
* @dev Get Creator TAO Setting Deprecation info
* @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation
*/
function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
return (
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId,
_creatorTAOSettingDeprecation.creatorTAOId,
_creatorTAOSettingDeprecation.settingId
);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == true &&
_settingDeprecation.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingDeprecation.locked = false;
} else {
// Reject the setting
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.rejected = true;
}
return true;
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == false &&
_settingDeprecation.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId)
);
// Update the setting data
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.locked = true;
_settingDeprecation.migrated = true;
uint256 _newSettingId = _settingDeprecation.pendingNewSettingId;
_settingDeprecation.pendingNewSettingId = 0;
_settingDeprecation.newSettingId = _newSettingId;
address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress;
_settingDeprecation.pendingNewSettingContractAddress = address(0);
_settingDeprecation.newSettingContractAddress = _newSettingContractAddress;
return true;
}
/**
* @dev Check if a setting exist and not rejected
* @param _settingId The ID of the setting
* @return true if exist. false otherwise
*/
function settingExist(uint256 _settingId) public view returns (bool) {
SettingData memory _settingData = settingDatas[_settingId];
return (_settingData.settingId == _settingId && _settingData.rejected == false);
}
/**
* @dev Get the latest ID of a deprecated setting, if exist
* @param _settingId The ID of the setting
* @return The latest setting ID
*/
function getLatestSettingId(uint256 _settingId) public view returns (uint256) {
(,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId);
while (_migrated && _newSettingId > 0) {
_settingId = _newSettingId;
(,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId);
}
return _settingId;
}
/***** Internal Method *****/
/**
* @dev Store setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) {
// Store setting data
SettingData storage _settingData = settingDatas[_settingId];
_settingData.settingId = _settingId;
_settingData.creatorNameId = _creatorNameId;
_settingData.creatorTAOId = _creatorTAOId;
_settingData.associatedTAOId = _associatedTAOId;
_settingData.settingName = _settingName;
_settingData.settingType = _settingType;
_settingData.pendingCreate = true;
_settingData.locked = true;
_settingData.settingDataJSON = _extraData;
// Store setting state
SettingState storage _settingState = settingStates[_settingId];
_settingState.settingId = _settingId;
return true;
}
/**
* @dev Store setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return true on success
*/
function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) {
// Make sure this setting exists
require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false);
// Make sure deprecation is not yet exist for this setting Id
require (settingDeprecations[_settingId].creatorNameId == address(0));
// Make sure newSettingId exists
require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false);
// Make sure the settingType matches
require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType);
// Store setting deprecation info
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
_settingDeprecation.settingId = _settingId;
_settingDeprecation.creatorNameId = _creatorNameId;
_settingDeprecation.creatorTAOId = _creatorTAOId;
_settingDeprecation.associatedTAOId = _associatedTAOId;
_settingDeprecation.pendingDeprecated = true;
_settingDeprecation.locked = true;
_settingDeprecation.pendingNewSettingId = _newSettingId;
_settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress;
return true;
}
}
/**
* @title AOTokenInterface
*/
contract AOTokenInterface is TheAO, TokenERC20 {
using SafeMath for uint256;
// To differentiate denomination of AO
uint256 public powerOfTen;
/***** NETWORK TOKEN VARIABLES *****/
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public stakedBalance;
mapping (address => uint256) public escrowedBalance;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event Stake(address indexed from, uint256 value);
event Unstake(address indexed from, uint256 value);
event Escrow(address indexed from, address indexed to, uint256 value);
event Unescrow(address indexed from, uint256 value);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
powerOfTen = 0;
decimals = 0;
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Prevent/Allow target from sending & receiving tokens
* @param target Address to be frozen
* @param freeze Either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyTheAO {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
* @param newSellPrice Price users can sell to the contract
* @param newBuyPrice Price users can buy from the contract
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
* @dev Stake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to stake
* @return true on success
*/
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance
emit Stake(_from, _value);
return true;
}
/**
* @dev Unstake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @return true on success
*/
function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough
stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unstake(_from, _value);
return true;
}
/**
* @dev Store `_value` from `_from` to `_to` in escrow
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens to put in escrow
* @return true on success
*/
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance
emit Escrow(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target` escrow balance
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive in escrow
*/
function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Escrow(this, target, mintedAmount);
return true;
}
/**
* @dev Release escrowed `_value` from `_from`
* @param _from The address of the sender
* @param _value The amount of escrowed network tokens to be released
* @return true on success
*/
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough
escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unescrow(_from, _value);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Whitelisted address transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Buy tokens from contract by sending ether
*/
function buy() public payable {
require (buyPrice > 0);
uint256 amount = msg.value.div(buyPrice);
_transfer(this, msg.sender, amount);
}
/**
* @dev Sell `amount` tokens to contract
* @param amount The amount of tokens to be sold
*/
function sell(uint256 amount) public {
require (sellPrice > 0);
address myAddress = this;
require (myAddress.balance >= amount.mul(sellPrice));
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount.mul(sellPrice));
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title AOToken
*/
contract AOToken is AOTokenInterface {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
// AO Dev Team addresses to receive Primordial/Network Tokens
address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52;
address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28;
AOSetting internal _aoSetting;
/***** PRIMORDIAL TOKEN VARIABLES *****/
uint256 public primordialTotalSupply;
uint256 public primordialTotalBought;
uint256 public primordialSellPrice;
uint256 public primordialBuyPrice;
// Total available primordial token for sale 1,125,899,906,842,620 AO+
uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620;
mapping (address => uint256) public primordialBalanceOf;
mapping (address => mapping (address => uint256)) public primordialAllowance;
// Mapping from owner's lot weighted multiplier to the amount of staked tokens
mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance;
event PrimordialTransfer(address indexed from, address indexed to, uint256 value);
event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value);
event PrimordialBurn(address indexed from, uint256 value);
event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier);
event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier);
uint256 public totalLots;
uint256 public totalBurnLots;
uint256 public totalConvertLots;
bool public networkExchangeEnded;
/**
* Stores Lot creation data (during network exchange)
*/
struct Lot {
bytes32 lotId;
uint256 multiplier; // This value is in 10^6, so 1000000 = 1
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account burns primordial token
*/
struct BurnLot {
bytes32 burnLotId;
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account converts network token to primordial token
*/
struct ConvertLot {
bytes32 convertLotId;
address lotOwner;
uint256 tokenAmount;
}
// Mapping from Lot ID to Lot object
mapping (bytes32 => Lot) internal lots;
// Mapping from Burn Lot ID to BurnLot object
mapping (bytes32 => BurnLot) internal burnLots;
// Mapping from Convert Lot ID to ConvertLot object
mapping (bytes32 => ConvertLot) internal convertLots;
// Mapping from owner to list of owned lot IDs
mapping (address => bytes32[]) internal ownedLots;
// Mapping from owner to list of owned burn lot IDs
mapping (address => bytes32[]) internal ownedBurnLots;
// Mapping from owner to list of owned convert lot IDs
mapping (address => bytes32[]) internal ownedConvertLots;
// Mapping from owner to his/her current weighted multiplier
mapping (address => uint256) internal ownerWeightedMultiplier;
// Mapping from owner to his/her max multiplier (multiplier of account's first Lot)
mapping (address => uint256) internal ownerMaxMultiplier;
// Event to be broadcasted to public when a lot is created
// multiplier value is in 10^6 to account for 6 decimal points
event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount);
// Event to be broadcasted to public when burn lot is created (when account burns primordial tokens)
event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn);
// Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens)
event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress)
AOTokenInterface(initialSupply, tokenName, tokenSymbol) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
_aoSetting = AOSetting(_aoSettingAddress);
powerOfTen = 0;
decimals = 0;
setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token
}
/**
* @dev Checks if buyer can buy primordial token
*/
modifier canBuyPrimordial(uint256 _sentAmount) {
require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange
* @param _aoDevTeam1 The first AO dev team address
* @param _aoDevTeam2 The second AO dev team address
*/
function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO {
aoDevTeam1 = _aoDevTeam1;
aoDevTeam2 = _aoDevTeam2;
}
/***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/
/**
* @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth
* @param newPrimordialSellPrice Price users can sell to the contract
* @param newPrimordialBuyPrice Price users can buy from the contract
*/
function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO {
primordialSellPrice = newPrimordialSellPrice;
primordialBuyPrice = newPrimordialBuyPrice;
}
/***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from`
* @param _from The address of the target
* @param _value The amount of Primordial tokens to stake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted balance is enough
require (primordialBalanceOf[_from] >= _value);
// Make sure the weighted multiplier is the same as account's current weighted multiplier
require (_weightedMultiplier == ownerWeightedMultiplier[_from]);
// Subtract from the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
// Add to the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value);
emit PrimordialStake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted staked balance is enough
require (primordialStakedBalance[_from][_weightedMultiplier] >= _value);
// Subtract from the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value);
// Add to the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value);
emit PrimordialUnstake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Send `_value` primordial tokens to `_to` on behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/***** PUBLIC METHODS *****/
/***** Primordial TOKEN PUBLIC METHODS *****/
/**
* @dev Buy Primordial tokens from contract by sending ether
*/
function buyPrimordialToken() public payable canBuyPrimordial(msg.value) {
(uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value);
require (tokenAmount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
}
// Send the primordial token to buyer and reward AO devs
_sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender);
// Send remainder budget back to buyer if exist
if (remainderBudget > 0) {
msg.sender.transfer(remainderBudget);
}
}
/**
* @dev Send `_value` Primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(msg.sender, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Send `_value` Primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @return true on success
*/
function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) {
primordialAllowance[msg.sender][_spender] = _value;
emit PrimordialApproval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approvePrimordialToken(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly
* and re-weight the account's multiplier after burn
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialToken(uint256 _value) public returns (bool success) {
require (primordialBalanceOf[msg.sender] >= _value);
require (calculateMaximumBurnAmount(msg.sender) >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value);
primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(msg.sender, _value);
emit PrimordialBurn(msg.sender, _value);
return true;
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from`
* and re-weight `_from`'s multiplier after burn
* @param _from The address of sender
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) {
require (primordialBalanceOf[_from] >= _value);
require (primordialAllowance[_from][msg.sender] >= _value);
require (calculateMaximumBurnAmount(_from) >= _value);
// Update `_from`'s multiplier
ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(_from, _value);
emit PrimordialBurn(_from, _value);
return true;
}
/**
* @dev Return all lot IDs owned by an address
* @param _lotOwner The address of the lot owner
* @return array of lot IDs
*/
function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedLots[_lotOwner];
}
/**
* @dev Return the total lots owned by an address
* @param _lotOwner The address of the lot owner
* @return total lots owner by the address
*/
function totalLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedLots[_lotOwner].length;
}
/**
* @dev Return the lot information at a given index of the lots list of the requested owner
* @param _lotOwner The address owning the lots list to be accessed
* @param _index uint256 representing the index to be accessed of the requested lots list
* @return id of the lot
* @return The address of the lot owner
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) {
require (_index < ownedLots[_lotOwner].length);
Lot memory _lot = lots[ownedLots[_lotOwner][_index]];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return the lot information at a given ID
* @param _lotId The lot ID in question
* @return id of the lot
* @return The lot owner address
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) {
Lot memory _lot = lots[_lotId];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return all Burn Lot IDs owned by an address
* @param _lotOwner The address of the burn lot owner
* @return array of Burn Lot IDs
*/
function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedBurnLots[_lotOwner];
}
/**
* @dev Return the total burn lots owned by an address
* @param _lotOwner The address of the burn lot owner
* @return total burn lots owner by the address
*/
function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedBurnLots[_lotOwner].length;
}
/**
* @dev Return the burn lot information at a given ID
* @param _burnLotId The burn lot ID in question
* @return id of the lot
* @return The address of the burn lot owner
* @return Primordial token amount in the burn lot
*/
function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) {
BurnLot memory _burnLot = burnLots[_burnLotId];
return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount);
}
/**
* @dev Return all Convert Lot IDs owned by an address
* @param _lotOwner The address of the convert lot owner
* @return array of Convert Lot IDs
*/
function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedConvertLots[_lotOwner];
}
/**
* @dev Return the total convert lots owned by an address
* @param _lotOwner The address of the convert lot owner
* @return total convert lots owner by the address
*/
function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedConvertLots[_lotOwner].length;
}
/**
* @dev Return the convert lot information at a given ID
* @param _convertLotId The convert lot ID in question
* @return id of the lot
* @return The address of the convert lot owner
* @return Primordial token amount in the convert lot
*/
function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) {
ConvertLot memory _convertLot = convertLots[_convertLotId];
return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount);
}
/**
* @dev Return the average weighted multiplier of all lots owned by an address
* @param _lotOwner The address of the lot owner
* @return the weighted multiplier of the address (in 10 ** 6)
*/
function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) {
return ownerWeightedMultiplier[_lotOwner];
}
/**
* @dev Return the max multiplier of an address
* @param _target The address to query
* @return the max multiplier of the address (in 10 ** 6)
*/
function maxMultiplierByAddress(address _target) public view returns (uint256) {
return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0;
}
/**
* @dev Calculate the primordial token multiplier, bonus network token percentage, and the
* bonus network token amount on a given lot when someone purchases primordial token
* during network exchange
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @return The multiplier in (10 ** 6)
* @return The bonus percentage
* @return The amount of network token as bonus
*/
function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
return (
AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier),
AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier),
AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier)
);
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* @param _account The address of the account
* @return The maximum primordial token amount to burn
*/
function calculateMaximumBurnAmount(address _account) public view returns (uint256) {
return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]);
}
/**
* @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens
* @param _account The address of the account
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) {
require (calculateMaximumBurnAmount(_account) >= _amountToBurn);
return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn);
}
/**
* @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token
* @param _account The address of the account
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) {
return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert);
}
/**
* @dev Convert `_value` of network tokens to primordial tokens
* and re-weight the account's multiplier after conversion
* @param _value The amount to convert
* @return true on success
*/
function convertToPrimordial(uint256 _value) public returns (bool success) {
require (balanceOf[msg.sender] >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value);
// Burn network token
burn(_value);
// mint primordial token
_mintPrimordialToken(msg.sender, _value);
// Store convert lot info
totalConvertLots++;
// Generate convert lot Id
bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots));
// Make sure no one owns this lot yet
require (convertLots[convertLotId].lotOwner == address(0));
ConvertLot storage convertLot = convertLots[convertLotId];
convertLot.convertLotId = convertLotId;
convertLot.lotOwner = msg.sender;
convertLot.tokenAmount = _value;
ownedConvertLots[msg.sender].push(convertLotId);
emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]);
return true;
}
/***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount of network tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transfer(_to, _value));
require (transferPrimordialToken(_to, _primordialValue));
return true;
}
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transferFrom(_from, _to, _value));
require (transferPrimordialTokenFrom(_from, _to, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of network tokens they can spend
* @return true on success
*/
function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.approve(_spender, _value));
require (approvePrimordialToken(_spender, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of Primordial Tokens they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) {
require (super.approveAndCall(_spender, _value, _extraData));
require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burn(_value));
require (burnPrimordialToken(_primordialValue));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from`
* @param _from The address of sender
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burnFrom(_from, _value));
require (burnPrimordialTokenFrom(_from, _primordialValue));
return true;
}
/***** INTERNAL METHODS *****/
/***** PRIMORDIAL TOKEN INTERNAL METHODS *****/
/**
* @dev Calculate the amount of token the buyer will receive and remaining budget if exist
* when he/she buys primordial token
* @param _budget The amount of ETH sent by buyer
* @return uint256 of the tokenAmount the buyer will receiver
* @return uint256 of the remaining budget, if exist
* @return bool whether or not the network exchange should end
*/
function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) {
// Calculate the amount of tokens
uint256 tokenAmount = _budget.div(primordialBuyPrice);
// If we need to return ETH to the buyer, in the case
// where the buyer sends more ETH than available primordial token to be purchased
uint256 remainderEth = 0;
// Make sure primordialTotalBought is not overflowing
bool shouldEndNetworkExchange = false;
if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) {
tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
shouldEndNetworkExchange = true;
remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice));
}
return (tokenAmount, remainderEth, shouldEndNetworkExchange);
}
/**
* @dev Actually sending the primordial token to buyer and reward AO devs accordingly
* @param tokenAmount The amount of primordial token to be sent to buyer
* @param to The recipient of the token
*/
function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal {
(uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
// Update primordialTotalBought
(uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount);
primordialTotalBought = primordialTotalBought.add(tokenAmount);
_createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount);
// Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus
uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier
uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR());
if (aoDevTeam1 != address(0)) {
_createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
if (aoDevTeam2 != address(0)) {
_createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
_mintToken(theAO, theAONetworkTokenBonusAmount);
}
/**
* @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account`
* during network exchange, and reward `_networkTokenBonusAmount` if exist
* @param _account Address of the lot owner
* @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot
* @param _multiplier The multiplier for this lot in (10 ** 6)
* @param _networkTokenBonusAmount The network token bonus amount
*/
function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal {
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _multiplier;
lot.lotOwner = _account;
lot.tokenAmount = _primordialTokenAmount;
ownedLots[_account].push(lotId);
ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
_mintPrimordialToken(_account, lot.tokenAmount);
_mintToken(_account, _networkTokenBonusAmount);
emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount);
}
/**
* @dev Create `mintedAmount` Primordial tokens and send it to `target`
* @param target Address to receive the Primordial tokens
* @param mintedAmount The amount of Primordial tokens it will receive
*/
function _mintPrimordialToken(address target, uint256 mintedAmount) internal {
primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount);
primordialTotalSupply = primordialTotalSupply.add(mintedAmount);
emit PrimordialTransfer(0, this, mintedAmount);
emit PrimordialTransfer(this, target, mintedAmount);
}
/**
* @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account`
* @param _account Address of lot owner
* @param _tokenAmount The amount of tokens
* @param _weightedMultiplier The multiplier of the lot (in 10^6)
* @return bytes32 of new created lot ID
*/
function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) {
require (_account != address(0));
require (_tokenAmount > 0);
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _weightedMultiplier;
lot.lotOwner = _account;
lot.tokenAmount = _tokenAmount;
ownedLots[_account].push(lotId);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
return lotId;
}
/**
* @dev Send `_value` Primordial tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough
require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender
primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient
emit PrimordialTransfer(_from, _to, _value);
assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances);
return true;
}
/**
* @dev Store burn lot information
* @param _account The address of the account
* @param _tokenAmount The amount of primordial tokens to burn
*/
function _createBurnLot(address _account, uint256 _tokenAmount) internal {
totalBurnLots++;
// Generate burn lot Id
bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots));
// Make sure no one owns this lot yet
require (burnLots[burnLotId].lotOwner == address(0));
BurnLot storage burnLot = burnLots[burnLotId];
burnLot.burnLotId = burnLotId;
burnLot.lotOwner = _account;
burnLot.tokenAmount = _tokenAmount;
ownedBurnLots[_account].push(burnLotId);
emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]);
}
/**
* @dev Get setting variables
* @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token
* @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token
* @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus
* @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier');
(uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier);
}
}
/**
* @title AOTreasury
*
* The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations
*/
contract AOTreasury is TheAO {
using SafeMath for uint256;
bool public paused;
bool public killed;
struct Denomination {
bytes8 name;
address denominationAddress;
}
// Mapping from denomination index to Denomination object
// The list is in order from lowest denomination to highest denomination
// i.e, denominations[1] is the base denomination
mapping (uint256 => Denomination) internal denominations;
// Mapping from denomination ID to index of denominations
mapping (bytes8 => uint256) internal denominationIndex;
uint256 public totalDenominations;
// Event to be broadcasted to public when a token exchange happens
event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/**
* @dev Checks if denomination is valid
*/
modifier isValidDenomination(bytes8 denominationName) {
require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO adds denomination and the contract address associated with it
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationAddress != address(0));
require (denominationIndex[denominationName] == 0);
totalDenominations++;
// Make sure the new denomination is higher than the previous
if (totalDenominations > 1) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress);
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen());
}
denominations[totalDenominations].name = denominationName;
denominations[totalDenominations].denominationAddress = denominationAddress;
denominationIndex[denominationName] = totalDenominations;
return true;
}
/**
* @dev The AO updates denomination address or activates/deactivates the denomination
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominationAddress != address(0));
uint256 _denominationNameIndex = denominationIndex[denominationName];
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
if (_denominationNameIndex > 1) {
AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress);
require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen());
}
if (_denominationNameIndex < totalDenominations) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress);
require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen());
}
denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get denomination info based on name
* @param denominationName The name to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominations[denominationIndex[denominationName]].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress);
return (
denominations[denominationIndex[denominationName]].name,
denominations[denominationIndex[denominationName]].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get denomination info by index
* @param index The index to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) {
require (index > 0 && index <= totalDenominations);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get base denomination info
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) {
require (totalDenominations > 1);
return getDenominationByIndex(1);
}
/**
* @dev convert token from `denominationName` denomination to base denomination,
* in this case it's similar to web3.toWei() functionality
*
* Example:
* 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount
* 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount
* 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount
*
* @param integerAmount uint256 of the integer amount to be converted
* @param fractionAmount uint256 of the frational amount to be converted
* @param denominationName bytes8 name of the token denomination
* @return uint256 converted amount in base denomination from target denomination
*/
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) {
if (denominationName.length > 0 &&
denominationIndex[denominationName] > 0 &&
denominations[denominationIndex[denominationName]].denominationAddress != address(0) &&
(integerAmount > 0 || fractionAmount > 0)) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint8 fractionNumDigits = _numDigits(fractionAmount);
require (fractionNumDigits <= _denominationToken.decimals());
uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen());
if (_denominationToken.decimals() == 0) {
fractionAmount = 0;
}
return baseInteger.add(fractionAmount);
} else {
return 0;
}
}
/**
* @dev convert token from base denomination to `denominationName` denomination,
* in this case it's similar to web3.fromWei() functionality
* @param integerAmount uint256 of the base amount to be converted
* @param denominationName bytes8 name of the target token denomination
* @return uint256 of the converted integer amount in target denomination
* @return uint256 of the converted fraction amount in target denomination
*/
function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen());
uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen()));
return (denominationInteger, denominationFraction);
}
/**
* @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination
* @param amount The amount of token to exchange
* @param fromDenominationName The origin denomination
* @param toDenominationName The target denomination
*/
function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) {
require (amount > 0);
Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]];
Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]];
AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress);
AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress);
require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount));
require (_toDenominationToken.mintToken(msg.sender, amount));
emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName);
}
/**
* @dev Return the highest possible denomination given a base amount
* @param amount The amount to be converted
* @return the denomination short name
* @return the denomination address
* @return the integer amount at the denomination level
* @return the fraction amount at the denomination level
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) {
uint256 integerAmount;
uint256 fractionAmount;
uint256 index;
for (uint256 i=totalDenominations; i>0; i--) {
Denomination memory _denomination = denominations[i];
(integerAmount, fractionAmount) = fromBase(amount, _denomination.name);
if (integerAmount > 0) {
index = i;
break;
}
}
require (index > 0 && index <= totalDenominations);
require (integerAmount > 0 || fractionAmount > 0);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
integerAmount,
fractionAmount,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/***** INTERNAL METHOD *****/
/**
* @dev count num of digits
* @param number uint256 of the nuumber to be checked
* @return uint8 num of digits
*/
function _numDigits(uint256 number) internal pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
contract Pathos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
contract Ethos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
/**
* @title TAOController
*/
contract TAOController {
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of TAO ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
}
// Store the name lookup for a Name/TAO
/**
* @title TAOFamily
*/
contract TAOFamily is TAOController {
using SafeMath for uint256;
address public taoFactoryAddress;
TAOFactory internal _taoFactory;
struct Child {
address taoId;
bool approved; // If false, then waiting for parent TAO approval
bool connected; // If false, then parent TAO want to remove this child TAO
}
struct Family {
address taoId;
address parentId; // The parent of this TAO ID (could be a Name or TAO)
uint256 childMinLogos;
mapping (uint256 => Child) children;
mapping (address => uint256) childInternalIdLookup;
uint256 totalChildren;
uint256 childInternalId;
}
mapping (address => Family) internal families;
// Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO
event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce);
// Event to be broadcasted to public when a TAO adds a child TAO
event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce);
// Event to be broadcasted to public when a TAO approves a child TAO
event ApproveChild(address indexed taoId, address childId, uint256 nonce);
// Event to be broadcasted to public when a TAO removes a child TAO
event RemoveChild(address indexed taoId, address childId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == taoFactoryAddress);
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a TAO ID exist in the list of families
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return families[_id].taoId != address(0);
}
/**
* @dev Store the Family info for a TAO
* @param _id The ID of the TAO
* @param _parentId The parent ID of this TAO
* @param _childMinLogos The min required Logos to create a TAO
* @return true on success
*/
function add(address _id, address _parentId, uint256 _childMinLogos)
public
isTAO(_id)
isNameOrTAO(_parentId)
onlyFactory returns (bool) {
require (!isExist(_id));
Family storage _family = families[_id];
_family.taoId = _id;
_family.parentId = _parentId;
_family.childMinLogos = _childMinLogos;
return true;
}
/**
* @dev Get Family info given a TAO ID
* @param _id The ID of the TAO
* @return the parent ID of this TAO (could be a Name/TAO)
* @return the min required Logos to create a child TAO
* @return the total child TAOs count
*/
function getFamilyById(address _id) public view returns (address, uint256, uint256) {
require (isExist(_id));
Family memory _family = families[_id];
return (
_family.parentId,
_family.childMinLogos,
_family.totalChildren
);
}
/**
* @dev Set min required Logos to create a child from this TAO
* @param _childMinLogos The min Logos to set
* @return the nonce for this transaction
*/
function updateChildMinLogos(address _id, uint256 _childMinLogos)
public
isTAO(_id)
senderIsName()
onlyAdvocate(_id) {
require (isExist(_id));
Family storage _family = families[_id];
_family.childMinLogos = _childMinLogos;
uint256 _nonce = _taoFactory.incrementNonce(_id);
require (_nonce > 0);
emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce);
}
/**
* @dev Check if `_childId` is a child TAO of `_taoId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to check
* @return true if yes. Otherwise return false.
*/
function isChild(address _taoId, address _childId) public view returns (bool) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family memory _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
return (
_childInternalId > 0 &&
_family.children[_childInternalId].approved &&
_family.children[_childInternalId].connected &&
_childFamily.parentId == _taoId
);
}
/**
* @dev Add child TAO
* @param _taoId The TAO ID to be added to
* @param _childId The ID to be added to as child TAO
*/
function addChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
onlyFactory returns (bool) {
require (!isChild(_taoId, _childId));
Family storage _family = families[_taoId];
require (_family.childInternalIdLookup[_childId] == 0);
_family.childInternalId++;
_family.childInternalIdLookup[_childId] = _family.childInternalId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
Child storage _child = _family.children[_family.childInternalId];
_child.taoId = _childId;
// If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected
// Otherwise, child TAO needs parent TAO approval
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
if (_taoAdvocate == _childAdvocate) {
_family.totalChildren++;
_child.approved = true;
_child.connected = true;
Family storage _childFamily = families[_childId];
_childFamily.parentId = _taoId;
}
emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce);
return true;
}
/**
* @dev Advocate of `_taoId` approves child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be approved
*/
function approveChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family storage _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
require (_childInternalId > 0 &&
!_family.children[_childInternalId].approved &&
!_family.children[_childInternalId].connected
);
_family.totalChildren++;
Child storage _child = _family.children[_childInternalId];
_child.approved = true;
_child.connected = true;
_childFamily.parentId = _taoId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit ApproveChild(_taoId, _childId, _nonce);
}
/**
* @dev Advocate of `_taoId` removes child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be removed
*/
function removeChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isChild(_taoId, _childId));
Family storage _family = families[_taoId];
_family.totalChildren--;
Child storage _child = _family.children[_family.childInternalIdLookup[_childId]];
_child.connected = false;
_family.childInternalIdLookup[_childId] = 0;
Family storage _childFamily = families[_childId];
_childFamily.parentId = address(0);
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit RemoveChild(_taoId, _childId, _nonce);
}
/**
* @dev Get list of child TAO IDs
* @param _taoId The TAO ID to be checked
* @param _from The starting index (start from 1)
* @param _to The ending index, (max is childInternalId)
* @return list of child TAO IDs
*/
function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) {
require (isExist(_taoId));
Family storage _family = families[_taoId];
require (_from >= 1 && _to >= _from && _family.childInternalId >= _to);
address[] memory _childIds = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0);
}
return _childIds;
}
}
// Store TAO's child information
/**
* @title TAOFactory
*
* The purpose of this contract is to allow node to create TAO
*/
contract TAOFactory is TheAO, TAOController {
using SafeMath for uint256;
address[] internal taos;
address public taoFamilyAddress;
address public nameTAOVaultAddress;
address public settingTAOId;
NameTAOLookup internal _nameTAOLookup;
TAOFamily internal _taoFamily;
AOSetting internal _aoSetting;
Logos internal _logos;
// Mapping from TAO ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when Advocate creates a TAO
event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_logos = Logos(_logosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if calling address can update TAO's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the TAOFamily Address
* @param _taoFamilyAddress The address of TAOFamily
*/
function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO {
require (_taoFamilyAddress != address(0));
taoFamilyAddress = _taoFamilyAddress;
_taoFamily = TAOFamily(taoFamilyAddress);
}
/**
* @dev The AO set settingTAOId (The TAO ID that holds the setting values)
* @param _settingTAOId The address of settingTAOId
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) {
settingTAOId = _settingTAOId;
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a TAO
* @param _taoId The ID of the TAO
* @return current nonce
*/
function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) {
// Check if _taoId exist
require (nonces[_taoId] > 0);
nonces[_taoId]++;
return nonces[_taoId];
}
/**
* @dev Name creates a TAO
* @param _name The name of the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _parentId The parent of this TAO (has to be a Name or TAO)
* @param _childMinLogos The min required Logos to create a child from this TAO
*/
function createTAO(
string _name,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _parentId,
uint256 _childMinLogos
) public senderIsName() isNameOrTAO(_parentId) {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
uint256 _parentCreateChildTAOMinLogos;
uint256 _createChildTAOMinLogos = _getSettingVariables();
if (AOLibrary.isTAO(_parentId)) {
(, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId);
}
if (_parentCreateChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos);
} else if (_createChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos);
}
// Create the TAO
address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[taoId]++;
// Store the name lookup information
require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId));
require (_taoFamily.add(taoId, _parentId, _childMinLogos));
taos.push(taoId);
emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId());
if (AOLibrary.isTAO(_parentId)) {
require (_taoFamily.addChild(_parentId, taoId));
}
}
/**
* @dev Get TAO information
* @param _taoId The ID of the TAO to be queried
* @return The name of the TAO
* @return The origin Name ID that created the TAO
* @return The name of Name that created the TAO
* @return The datHash of the TAO
* @return The database of the TAO
* @return The keyValue of the TAO
* @return The contentId of the TAO
* @return The typeId of the TAO
*/
function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) {
TAO _tao = TAO(_taoId);
return (
_tao.name(),
_tao.originId(),
Name(_tao.originId()).name(),
_tao.datHash(),
_tao.database(),
_tao.keyValue(),
_tao.contentId(),
_tao.typeId()
);
}
/**
* @dev Get total TAOs count
* @return total TAOs count
*/
function getTotalTAOsCount() public view returns (uint256) {
return taos.length;
}
/**
* @dev Get list of TAO IDs
* @param _from The starting index
* @param _to The ending index
* @return list of TAO IDs
*/
function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from && taos.length > _to);
address[] memory _taos = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_taos[i.sub(_from)] = taos[i];
}
return _taos;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The Name of the TAO
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
* @return The name of the Name that created the signature
* @return The Position of the Name that created the signature.
* 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker
*/
function validateTAOSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) {
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) {
return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name)));
} else {
return (false, "", 0);
}
}
/***** INTERNAL METHOD *****/
/**
* @dev Check whether or not the address recovered from the signature is valid
* @param _validateAddress The ETH address to be validated (optional)
* @param _signatureAddress The address recovered from the signature
* @param _taoId The ID of the TAO
* @param _nonce The signed uint256 nonce
* @return true if valid. false otherwise
*/
function _isTAOSignatureAddressValid(
address _validateAddress,
address _signatureAddress,
address _taoId,
uint256 _nonce
) internal view returns (bool) {
if (_validateAddress != address(0)) {
return (_nonce == nonces[_taoId].add(1) &&
_signatureAddress == _validateAddress &&
_nameTAOPosition.senderIsPosition(_validateAddress, _taoId)
);
} else {
return (
_nonce == nonces[_taoId].add(1) &&
_nameTAOPosition.senderIsPosition(_signatureAddress, _taoId)
);
}
}
/**
* @dev Internal function to get the TAO Id by name
* @param _name The name of the TAO
* @return the TAO ID
*/
function _getTAOIdByName(string _name) internal view returns (address) {
return _nameTAOLookup.getAddressByName(_name);
}
/**
* @dev Get setting variables
* @return createChildTAOMinLogos The minimum required Logos to create a TAO
*/
function _getSettingVariables() internal view returns (uint256) {
(uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos');
return createChildTAOMinLogos;
}
}
/**
* @title NameTAOPosition
*/
contract NameTAOPosition is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
NameFactory internal _nameFactory;
TAOFactory internal _taoFactory;
struct Position {
address advocateId;
address listenerId;
address speakerId;
bool created;
}
mapping (address => Position) internal positions;
// Event to be broadcasted to public when current Advocate of TAO sets New Advocate
event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener
event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker
event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
nameTAOPositionAddress = address(this);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of a Name/TAO ID
*/
modifier onlyAdvocate(address _id) {
require (senderIsAdvocate(msg.sender, _id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name/TAO ID exist in the list
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return positions[_id].created;
}
/**
* @dev Check whether or not eth address is advocate of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsAdvocate(address _sender, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender));
}
/**
* @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsPosition(address _sender, address _id) public view returns (bool) {
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == address(0)) {
return false;
} else {
return (positions[_id].created &&
(positions[_id].advocateId == _nameId ||
positions[_id].listenerId == _nameId ||
positions[_id].speakerId == _nameId
)
);
}
}
/**
* @dev Check whether or not _nameId is advocate of _id
* @param _nameId The name ID to be checked
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function nameIsAdvocate(address _nameId, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameId);
}
/**
* @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO
* @param _sender The ETH address that to check
* @param _id The ID of the Name/TAO
* @return 1 if Advocate. 2 if Listener. 3 if Speaker
*/
function determinePosition(address _sender, address _id) public view returns (uint256) {
require (senderIsPosition(_sender, _id));
Position memory _position = positions[_id];
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == _position.advocateId) {
return 1;
} else if (_nameId == _position.listenerId) {
return 2;
} else {
return 3;
}
}
/**
* @dev Add Position for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _advocateId The Advocate ID of the Name/TAO
* @param _listenerId The Listener ID of the Name/TAO
* @param _speakerId The Speaker ID of the Name/TAO
* @return true on success
*/
function add(address _id, address _advocateId, address _listenerId, address _speakerId)
public
isNameOrTAO(_id)
isName(_advocateId)
isNameOrTAO(_listenerId)
isNameOrTAO(_speakerId)
onlyFactory returns (bool) {
require (!isExist(_id));
Position storage _position = positions[_id];
_position.advocateId = _advocateId;
_position.listenerId = _listenerId;
_position.speakerId = _speakerId;
_position.created = true;
return true;
}
/**
* @dev Get Name/TAO's Position info
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
* @return the Listener ID of Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getPositionById(address _id) public view returns (address, address, address) {
require (isExist(_id));
Position memory _position = positions[_id];
return (
_position.advocateId,
_position.listenerId,
_position.speakerId
);
}
/**
* @dev Get Name/TAO's Advocate
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
*/
function getAdvocate(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.advocateId;
}
/**
* @dev Get Name/TAO's Listener
* @param _id The ID of the Name/TAO
* @return the Listener ID of Name/TAO
*/
function getListener(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.listenerId;
}
/**
* @dev Get Name/TAO's Speaker
* @param _id The ID of the Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getSpeaker(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.speakerId;
}
/**
* @dev Set Advocate for a TAO
* @param _taoId The ID of the TAO
* @param _newAdvocateId The new advocate ID to be set
*/
function setAdvocate(address _taoId, address _newAdvocateId)
public
isTAO(_taoId)
isName(_newAdvocateId)
senderIsName()
onlyAdvocate(_taoId) {
Position storage _position = positions[_taoId];
address _currentAdvocateId = _position.advocateId;
_position.advocateId = _newAdvocateId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce);
}
/**
* @dev Set Listener for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newListenerId The new listener ID to be set
*/
function setListener(address _id, address _newListenerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newListenerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Listener can only be a Name
// If _id is a TAO, then new Listener can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newListenerId));
}
Position storage _position = positions[_id];
address _currentListenerId = _position.listenerId;
_position.listenerId = _newListenerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce);
}
/**
* @dev Set Speaker for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newSpeakerId The new speaker ID to be set
*/
function setSpeaker(address _id, address _newSpeakerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newSpeakerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Speaker can only be a Name
// If _id is a TAO, then new Speaker can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newSpeakerId));
}
Position storage _position = positions[_id];
address _currentSpeakerId = _position.speakerId;
_position.speakerId = _newSpeakerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce);
}
}
/**
* @title AOSetting
*
* This contract stores all AO setting variables
*/
contract AOSetting {
address public aoSettingAttributeAddress;
address public aoUintSettingAddress;
address public aoBoolSettingAddress;
address public aoAddressSettingAddress;
address public aoBytesSettingAddress;
address public aoStringSettingAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
AOSettingAttribute internal _aoSettingAttribute;
AOUintSetting internal _aoUintSetting;
AOBoolSetting internal _aoBoolSetting;
AOAddressSetting internal _aoAddressSetting;
AOBytesSetting internal _aoBytesSetting;
AOStringSetting internal _aoStringSetting;
uint256 public totalSetting;
/**
* Mapping from associatedTAOId's setting name to Setting ID.
*
* Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup,
* use nested mapping to achieve the same result.
*
* The setting's name needs to be converted to bytes32 since solidity does not support mapping by string.
*/
mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup;
// Mapping from updateHashKey to it's settingId
mapping (bytes32 => uint256) public updateHashLookup;
// Event to be broadcasted to public when a setting is created and waiting for approval
event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId);
// Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId
event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
// Event to be broadcasted to public when a proposed update for a setting is created
event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId);
// Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId
event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId
event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate);
// Event to be broadcasted to public when a setting deprecation is created and waiting for approval
event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId);
// Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId
event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress,
address _nameTAOPositionAddress,
address _aoSettingAttributeAddress,
address _aoUintSettingAddress,
address _aoBoolSettingAddress,
address _aoAddressSettingAddress,
address _aoBytesSettingAddress,
address _aoStringSettingAddress) public {
aoSettingAttributeAddress = _aoSettingAttributeAddress;
aoUintSettingAddress = _aoUintSettingAddress;
aoBoolSettingAddress = _aoBoolSettingAddress;
aoAddressSettingAddress = _aoAddressSettingAddress;
aoBytesSettingAddress = _aoBytesSettingAddress;
aoStringSettingAddress = _aoStringSettingAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress);
_aoUintSetting = AOUintSetting(_aoUintSettingAddress);
_aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress);
_aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress);
_aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress);
_aoStringSetting = AOStringSetting(_aoStringSettingAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_settingName` of `_associatedTAOId` is taken
*/
modifier settingNameNotTaken(string _settingName, address _associatedTAOId) {
require (settingNameExist(_settingName, _associatedTAOId) == false);
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** Public Methods *****/
/**
* @dev Check whether or not a setting name of an associatedTAOId exist
* @param _settingName The human-readable name of the setting
* @param _associatedTAOId The taoId that the setting affects
* @return true if yes. false otherwise
*/
function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) {
return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0);
}
/**
* @dev Advocate of _creatorTAOId adds a uint setting
* @param _settingName The human-readable name of the setting
* @param _value The uint256 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoUintSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bool setting
* @param _settingName The human-readable name of the setting
* @param _value The bool value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBoolSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds an address setting
* @param _settingName The human-readable name of the setting
* @param _value The address value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoAddressSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bytes32 setting
* @param _settingName The human-readable name of the setting
* @param _value The bytes32 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBytesSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a string setting
* @param _settingName The human-readable name of the setting
* @param _value The string value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoStringSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingCreation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved));
(,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId);
if (!_approved) {
// Clear the settingName from nameSettingLookup so it can be added again in the future
delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingCreation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate));
(,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new uint256 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoUintSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bool value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBoolSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new address value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoAddressSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bytes32 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBytesSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new string value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoStringSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _approved Whether to approve or reject
*/
function approveSettingUpdate(uint256 _settingId, bool _approved) public {
address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
(,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId);
require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved));
emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingUpdate(uint256 _settingId) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate));
(,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate);
}
/**
* @dev Advocate of _creatorTAOId adds a setting deprecation
* @param _settingId The ID of the setting to be deprecated
* @param _newSettingId The new setting ID to route
* @param _newSettingContractAddress The new setting contract address to route
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
*/
function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) {
(bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress);
emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingDeprecation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved));
(,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingDeprecation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate));
(,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Get setting Id given an associatedTAOId and settingName
* @param _associatedTAOId The ID of the AssociatedTAO
* @param _settingName The name of the setting
* @return the ID of the setting
*/
function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) {
return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
/**
* @dev Get setting values by setting ID.
* Will throw error if the setting is not exist or rejected.
* @param _settingId The ID of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) {
require (_aoSettingAttribute.settingExist(_settingId));
_settingId = _aoSettingAttribute.getLatestSettingId(_settingId);
return (
_aoUintSetting.settingValue(_settingId),
_aoBoolSetting.settingValue(_settingId),
_aoAddressSetting.settingValue(_settingId),
_aoBytesSetting.settingValue(_settingId),
_aoStringSetting.settingValue(_settingId)
);
}
/**
* @dev Get setting values by taoId and settingName.
* Will throw error if the setting is not exist or rejected.
* @param _taoId The ID of the TAO
* @param _settingName The name of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) {
return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName));
}
/***** Internal Method *****/
/**
* @dev Store setting creation data
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal {
// Make sure _settingType is in supported list
require (_settingType >= 1 && _settingType <= 5);
// Store nameSettingLookup
nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting;
// Store setting data/state
(bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Move value of _settingId from pending variable to setting variable
* @param _settingId The ID of the setting
* @param _settingType The type of the setting
*/
function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal {
// If settingType == uint256
if (_settingType == 1) {
_aoUintSetting.movePendingToSetting(_settingId);
} else if (_settingType == 2) {
// Else if settingType == bool
_aoBoolSetting.movePendingToSetting(_settingId);
} else if (_settingType == 3) {
// Else if settingType == address
_aoAddressSetting.movePendingToSetting(_settingId);
} else if (_settingType == 4) {
// Else if settingType == bytes32
_aoBytesSetting.movePendingToSetting(_settingId);
} else {
// Else if settingType == string
_aoStringSetting.movePendingToSetting(_settingId);
}
}
}
/**
* @title AOEarning
*
* This contract stores the earning from staking/hosting content on AO
*/
contract AOEarning is TheAO {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
address public baseDenominationAddress;
address public treasuryAddress;
address public nameFactoryAddress;
address public pathosAddress;
address public ethosAddress;
bool public paused;
bool public killed;
AOToken internal _baseAO;
AOTreasury internal _treasury;
NameFactory internal _nameFactory;
Pathos internal _pathos;
Ethos internal _ethos;
AOSetting internal _aoSetting;
// Total earning from staking content from all nodes
uint256 public totalStakeContentEarning;
// Total earning from hosting content from all nodes
uint256 public totalHostContentEarning;
// Total The AO earning
uint256 public totalTheAOEarning;
// Mapping from address to his/her earning from content that he/she staked
mapping (address => uint256) public stakeContentEarning;
// Mapping from address to his/her earning from content that he/she hosted
mapping (address => uint256) public hostContentEarning;
// Mapping from address to his/her network price earning
// i.e, when staked amount = filesize
mapping (address => uint256) public networkPriceEarning;
// Mapping from address to his/her content price earning
// i.e, when staked amount > filesize
mapping (address => uint256) public contentPriceEarning;
// Mapping from address to his/her inflation bonus
mapping (address => uint256) public inflationBonusAccrued;
struct Earning {
bytes32 purchaseId;
uint256 paymentEarning;
uint256 inflationBonus;
uint256 pathosAmount;
uint256 ethosAmount;
}
// Mapping from address to earning from staking content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public stakeEarnings;
// Mapping from address to earning from hosting content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public hostEarnings;
// Mapping from purchase ID to earning for The AO
mapping (bytes32 => Earning) public theAOEarnings;
// Mapping from stake ID to it's total earning from staking
mapping (bytes32 => uint256) public totalStakedContentStakeEarning;
// Mapping from stake ID to it's total earning from hosting
mapping (bytes32 => uint256) public totalStakedContentHostEarning;
// Mapping from stake ID to it's total earning earned by The AO
mapping (bytes32 => uint256) public totalStakedContentTheAOEarning;
// Mapping from content host ID to it's total earning
mapping (bytes32 => uint256) public totalHostContentEarningById;
// Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earning is released from escrow
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content
event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when host's Name earns Ethos when a node buys a content
event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _nameFactoryAddress The address of NameFactory
* @param _pathosAddress The address of Pathos
* @param _ethosAddress The address of Ethos
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
pathosAddress = _pathosAddress;
ethosAddress = _ethosAddress;
_aoSetting = AOSetting(_aoSettingAddress);
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_nameFactory = NameFactory(_nameFactoryAddress);
_pathos = Pathos(_pathosAddress);
_ethos = Ethos(_ethosAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Calculate the content creator/host/The AO earning when request node buys the content.
* Also at this stage, all of the earnings are stored in escrow
* @param _buyer The request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function calculateEarning(
address _buyer,
bytes32 _purchaseId,
uint256 _networkAmountStaked,
uint256 _primordialAmountStaked,
uint256 _primordialWeightedMultiplierStaked,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) public isContractActive inWhitelist returns (bool) {
// Split the payment earning between content creator and host and store them in escrow
_escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
// Calculate the inflation bonus earning for content creator/node/The AO in escrow
_escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
return true;
}
/**
* @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID to check
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _stakeOwner The address of the stake owner
* @param _host The address of the node that host the file
* @return true on success
*/
function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) {
// Release the earning in escrow for stake owner
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0);
// Release the earning in escrow for host
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1);
// Release the earning in escrow for The AO
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Calculate the payment split for content creator/host and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal {
(uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType);
(uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning);
_escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount);
}
/**
* @dev Calculate the inflation bonus amount
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @return the bonus network amount
*/
function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
return _networkBonus.add(_primordialBonus);
}
/**
* @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _inflationBonusAmount The amount of inflation bonus earning
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowInflationBonus(
bytes32 _purchaseId,
uint256 _inflationBonusAmount,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) internal {
(, uint256 theAOCut,) = _getSettingVariables();
if (_inflationBonusAmount > 0) {
// Store how much the content creator earns in escrow
uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.inflationBonus = _stakeOwnerInflationBonus;
require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus));
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0);
// Store how much the host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus);
require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus));
emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1);
// Store how much the The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus));
emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2);
} else {
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0);
emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1);
emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2);
}
}
/**
* @dev Release the escrowed earning for a specific purchase ID for an account
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _account The address of account that made the earning (content creator/host)
* @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO)
*/
function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal {
// Make sure the recipient type is valid
require (_recipientType >= 0 && _recipientType <= 2);
uint256 _paymentEarning;
uint256 _inflationBonus;
uint256 _totalEarning;
uint256 _pathosAmount;
uint256 _ethosAmount;
if (_recipientType == 0) {
Earning storage _earning = stakeEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_pathosAmount = _earning.pathosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning);
stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning);
totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the content creator/stake owner with some Pathos
require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount));
emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount);
} else if (_recipientType == 1) {
_earning = hostEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_ethosAmount = _earning.ethosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalHostContentEarning = totalHostContentEarning.add(_totalEarning);
hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning);
totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning);
totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the host node with some Ethos
require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount));
emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount);
} else {
_earning = theAOEarnings[_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalTheAOEarning = totalTheAOEarning.add(_totalEarning);
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning);
}
require (_baseAO.unescrowFrom(_account, _totalEarning));
emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType);
}
/**
* @dev Get setting variables
* @return inflationRate The rate to use when calculating inflation bonus
* @return theAOCut The rate to use when calculating the AO earning
* @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256) {
(uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate');
(uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut');
(uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate');
return (inflationRate, theAOCut, theAOEthosEarnedRate);
}
/**
* @dev Calculate the payment split for content creator and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @return The stake owner's earning amount
* @return The pathos earned from this transaction
*/
function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.purchaseId = _purchaseId;
// Store how much the content creator (stake owner) earns in escrow
// If content is AO Content Usage Type, stake owner earns 0%
// and all profit goes to the serving host node
_stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
// Pathos = Price X Node Share X Inflation Rate
_stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning));
emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0);
return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount);
}
/**
* @dev Calculate the payment split for host node and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _host The address of the host node
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @param _stakeOwnerEarning The stake owner's earning amount
* @return The ethos earned from this transaction
*/
function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
// Store how much the node host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.purchaseId = _purchaseId;
_hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning);
// Ethos = Price X Creator Share X Inflation Rate
_hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
if (_isAOContentUsageType) {
require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning));
} else {
// If not AO Content usage type, we want to mint to the host
require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning));
}
emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1);
return _hostEarning.ethosAmount;
}
/**
* @dev Calculate the earning for The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _pathosAmount The amount of pathos earned by stake owner
* @param _ethosAmount The amount of ethos earned by host node
*/
function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal {
(,,uint256 theAOEthosEarnedRate) = _getSettingVariables();
// Store how much The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.purchaseId = _purchaseId;
// Pathos + X% of Ethos
_theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR()));
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning));
emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2);
}
}
/**
* @title AOContent
*
* The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens
* on his/her content
*/
contract AOContent is TheAO {
using SafeMath for uint256;
uint256 public totalContents;
uint256 public totalContentHosts;
uint256 public totalStakedContents;
uint256 public totalPurchaseReceipts;
address public settingTAOId;
address public baseDenominationAddress;
address public treasuryAddress;
AOToken internal _baseAO;
AOTreasury internal _treasury;
AOEarning internal _earning;
AOSetting internal _aoSetting;
NameTAOPosition internal _nameTAOPosition;
bool public paused;
bool public killed;
struct Content {
bytes32 contentId;
address creator;
/**
* baseChallenge is the content's PUBLIC KEY
* When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY)
* so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node
* submit
*/
string baseChallenge;
uint256 fileSize;
bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content
address taoId;
bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO
uint8 updateTAOContentStateV;
bytes32 updateTAOContentStateR;
bytes32 updateTAOContentStateS;
string extraData;
}
struct StakedContent {
bytes32 stakeId;
bytes32 contentId;
address stakeOwner;
uint256 networkAmount; // total network token staked in base denomination
uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination)
uint256 primordialWeightedMultiplier;
uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000
bool active; // true if currently staked, false when unstaked
uint256 createdOnTimestamp;
}
struct ContentHost {
bytes32 contentHostId;
bytes32 stakeId;
address host;
/**
* encChallenge is the content's PUBLIC KEY unique to the host
*/
string encChallenge;
string contentDatKey;
string metadataDatKey;
}
struct PurchaseReceipt {
bytes32 purchaseId;
bytes32 contentHostId;
address buyer;
uint256 price;
uint256 amountPaidByBuyer; // total network token paid in base denomination
uint256 amountPaidByAO; // total amount paid by AO
string publicKey; // The public key provided by request node
address publicAddress; // The public address provided by request node
uint256 createdOnTimestamp;
}
// Mapping from Content index to the Content object
mapping (uint256 => Content) internal contents;
// Mapping from content ID to index of the contents list
mapping (bytes32 => uint256) internal contentIndex;
// Mapping from StakedContent index to the StakedContent object
mapping (uint256 => StakedContent) internal stakedContents;
// Mapping from stake ID to index of the stakedContents list
mapping (bytes32 => uint256) internal stakedContentIndex;
// Mapping from ContentHost index to the ContentHost object
mapping (uint256 => ContentHost) internal contentHosts;
// Mapping from content host ID to index of the contentHosts list
mapping (bytes32 => uint256) internal contentHostIndex;
// Mapping from PurchaseReceipt index to the PurchaseReceipt object
mapping (uint256 => PurchaseReceipt) internal purchaseReceipts;
// Mapping from purchase ID to index of the purchaseReceipts list
mapping (bytes32 => uint256) internal purchaseReceiptIndex;
// Mapping from buyer's content host ID to the buy ID
// To check whether or not buyer has bought/paid for a content
mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts;
// Event to be broadcasted to public when `content` is stored
event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType);
// Event to be broadcasted to public when `stakeOwner` stakes a new content
event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp);
// Event to be broadcasted to public when a node hosts a content
event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey);
// Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage
event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage);
// Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content
event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier);
// Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content
event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId);
// Event to be broadcasted to public when `stakeOwner` re-stakes an existing content
event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier);
// Event to be broadcasted to public when a request node buys a content
event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp);
// Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State
event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _earningAddress The address of AOEarning
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public {
settingTAOId = _settingTAOId;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
nameTAOPositionAddress = _nameTAOPositionAddress;
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_earning = AOEarning(_earningAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
*/
function stakeAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage));
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_aoContent,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
_profitPercentage
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
*/
function stakeCreativeCommonsContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize);
(,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_creativeCommons,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
*/
function stakeTAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
address _taoId)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (
_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize &&
_nameTAOPosition.senderIsPosition(msg.sender, _taoId)
);
(,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_taoContent,
_taoId
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Set profit percentage on existing staked content
* Will throw error if this is a Creative Commons/T(AO) Content
* @param _stakeId The ID of the staked content
* @param _profitPercentage The new value to be set
*/
function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive {
require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR());
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure we are updating profit percentage for AO Content only
// Creative Commons/T(AO) Content has 0 profit percentage
require (_isAOContentUsageType(_stakedContent.contentId));
_stakedContent.profitPercentage = _profitPercentage;
emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage);
}
/**
* @dev Set extra data on existing content
* @param _contentId The ID of the content
* @param _extraData some extra information to send to the contract for a content
*/
function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure the content creator is the same as the sender
require (_content.creator == msg.sender);
_content.extraData = _extraData;
}
/**
* @dev Return content info at a given ID
* @param _contentId The ID of the content
* @return address of the creator
* @return file size of the content
* @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @return The TAO ID for this content (if this is a T(AO) Content)
* @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO
* @return The V part of signature that is used to update the TAO Content State
* @return The R part of signature that is used to update the TAO Content State
* @return The S part of signature that is used to update the TAO Content State
* @return the extra information sent to the contract when creating a content
*/
function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content memory _content = contents[contentIndex[_contentId]];
return (
_content.creator,
_content.fileSize,
_content.contentUsageType,
_content.taoId,
_content.taoContentState,
_content.updateTAOContentStateV,
_content.updateTAOContentStateR,
_content.updateTAOContentStateS,
_content.extraData
);
}
/**
* @dev Return content host info at a given ID
* @param _contentHostId The ID of the hosted content
* @return The ID of the staked content
* @return address of the host
* @return the dat key of the content
* @return the dat key of the content's metadata
*/
function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
return (
_contentHost.stakeId,
_contentHost.host,
_contentHost.contentDatKey,
_contentHost.metadataDatKey
);
}
/**
* @dev Return staked content information at a given ID
* @param _stakeId The ID of the staked content
* @return The ID of the content being staked
* @return address of the staked content's owner
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the profit percentage of the content
* @return status of the staked content
* @return the timestamp when the staked content was created
*/
function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
return (
_stakedContent.contentId,
_stakedContent.stakeOwner,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.active,
_stakedContent.createdOnTimestamp
);
}
/**
* @dev Unstake existing staked content and refund partial staked amount to the stake owner
* Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to
* the mininum required to pay the fileSize
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to unstake
* @param _networkFractionAmount The fraction amount of network token to unstake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to unstake
*/
function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the staked content has enough balance to unstake
require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize));
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount);
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount);
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Unstake existing staked content and refund the total staked amount to the stake owner
* @param _stakeId The ID of the staked content
*/
function unstakeContent(bytes32 _stakeId) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
_stakedContent.active = false;
if (_stakedContent.networkAmount > 0) {
uint256 _unstakeNetworkAmount = _stakedContent.networkAmount;
_stakedContent.networkAmount = 0;
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_stakedContent.primordialAmount > 0) {
uint256 _primordialAmount = _stakedContent.primordialAmount;
uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier;
_stakedContent.primordialAmount = 0;
_stakedContent.primordialWeightedMultiplier = 0;
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier));
}
emit UnstakeContent(_stakedContent.stakeOwner, _stakeId);
}
/**
* @dev Stake existing content with more tokens (this is to increase the price)
*
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier)
*/
function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount));
// Make sure we can stake primordial token
// If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier`
// i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first
if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) {
require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier);
}
_stakedContent.active = true;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount);
require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount);
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Determine the content price hosted by a host
* @param _contentHostId The content host ID to be checked
* @return the price of the content
*/
function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) {
// Make sure content host exist
require (contentHostIndex[_contentHostId] > 0);
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure content is currently staked
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
return _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
}
/**
* @dev Determine the how much the content is paid by AO given a contentHostId
* @param _contentHostId The content host ID to be checked
* @return the amount paid by AO
*/
function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) {
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
if (_isAOContentUsageType(_contentId)) {
return 0;
} else {
return contentHostPrice(_contentHostId);
}
}
/**
* @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content
* @param _contentHostId The ID of hosted content
* @param _networkIntegerAmount The integer amount of network token to pay
* @param _networkFractionAmount The fraction amount of network token to pay
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _publicKey The public key of the request node
* @param _publicAddress The public address of the request node
*/
function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
// Make sure public key is not empty
require (bytes(_publicKey).length > 0);
// Make sure public address is valid
require (_publicAddress != address(0));
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]];
// Make sure the content currently has stake
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the buyer has not bought this content previously
require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0);
// Make sure the token amount can pay for the content price
if (_isAOContentUsageType(_stakedContent.contentId)) {
require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination));
}
// Increment totalPurchaseReceipts;
totalPurchaseReceipts++;
// Generate purchaseId
bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId));
PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts];
// Make sure the node doesn't buy the same content twice
require (_purchaseReceipt.buyer == address(0));
_purchaseReceipt.purchaseId = _purchaseId;
_purchaseReceipt.contentHostId = _contentHostId;
_purchaseReceipt.buyer = msg.sender;
// Update the receipt with the correct network amount
_purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
_purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId);
_purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO);
_purchaseReceipt.publicKey = _publicKey;
_purchaseReceipt.publicAddress = _publicAddress;
_purchaseReceipt.createdOnTimestamp = now;
purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts;
buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId;
// Calculate content creator/host/The AO earning from this purchase and store them in escrow
require (_earning.calculateEarning(
msg.sender,
_purchaseId,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.stakeOwner,
_contentHost.host,
_isAOContentUsageType(_stakedContent.contentId)
));
emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp);
}
/**
* @dev Return purchase receipt info at a given ID
* @param _purchaseId The ID of the purchased content
* @return The ID of the content host
* @return address of the buyer
* @return price of the content
* @return amount paid by AO
* @return amount paid by Buyer
* @return request node's public key
* @return request node's public address
* @return created on timestamp
*/
function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
return (
_purchaseReceipt.contentHostId,
_purchaseReceipt.buyer,
_purchaseReceipt.price,
_purchaseReceipt.amountPaidByAO,
_purchaseReceipt.amountPaidByBuyer,
_purchaseReceipt.publicKey,
_purchaseReceipt.publicAddress,
_purchaseReceipt.createdOnTimestamp
);
}
/**
* @dev Request node wants to become a distribution node after buying the content
* Also, if this transaction succeeds, contract will release all of the earnings that are
* currently in escrow for content creator/host/The AO
*/
function becomeHost(
bytes32 _purchaseId,
uint8 _baseChallengeV,
bytes32 _baseChallengeR,
bytes32 _baseChallengeS,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey
) public isContractActive {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
// Make sure the purchase receipt owner is the same as the sender
require (_purchaseReceipt.buyer == msg.sender);
// Verify that the file is not tampered by validating the base challenge signature
// The signed base challenge key should match the one from content creator
Content memory _content = contents[contentIndex[_contentId]];
require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress);
_hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey);
// Release earning from escrow
require (_earning.releaseEarning(
_stakeId,
_purchaseReceipt.contentHostId,
_purchaseId,
(_purchaseReceipt.amountPaidByBuyer > _content.fileSize),
stakedContents[stakedContentIndex[_stakeId]].stakeOwner,
contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host)
);
}
/**
* @dev Update the TAO Content State of a T(AO) Content
* @param _contentId The ID of the Content
* @param _taoId The ID of the TAO that initiates the update
* @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _updateTAOContentStateV The V part of the signature for this update
* @param _updateTAOContentStateR The R part of the signature for this update
* @param _updateTAOContentStateS The S part of the signature for this update
*/
function updateTAOContentState(
bytes32 _contentId,
address _taoId,
bytes32 _taoContentState,
uint8 _updateTAOContentStateV,
bytes32 _updateTAOContentStateR,
bytes32 _updateTAOContentStateS
) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
require (AOLibrary.isTAO(_taoId));
(,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables();
require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO);
address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker
require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId));
require (_content.contentUsageType == _contentUsageType_taoContent);
_content.taoContentState = _taoContentState;
_content.updateTAOContentStateV = _updateTAOContentStateV;
_content.updateTAOContentStateR = _updateTAOContentStateR;
_content.updateTAOContentStateS = _updateTAOContentStateS;
emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState);
}
/***** INTERNAL METHODS *****/
/**
* @dev Store the content information (content creation during staking)
* @param _creator the address of the content creator
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _fileSize The size of the file
* @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
* @return the ID of the content
*/
function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) {
// Increment totalContents
totalContents++;
// Generate contentId
bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents));
Content storage _content = contents[totalContents];
// Make sure the node does't store the same content twice
require (_content.creator == address(0));
(,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables();
_content.contentId = _contentId;
_content.creator = _creator;
_content.baseChallenge = _baseChallenge;
_content.fileSize = _fileSize;
_content.contentUsageType = _contentUsageType;
// If this is a TAO Content
if (_contentUsageType == contentUsageType_taoContent) {
_content.taoContentState = taoContentState_submitted;
_content.taoId = _taoId;
}
contentIndex[_contentId] = totalContents;
emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType);
return _content.contentId;
}
/**
* @dev Add the distribution node info that hosts the content
* @param _host the address of the host
* @param _stakeId The ID of the staked content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
*/
function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal {
require (bytes(_encChallenge).length > 0);
require (bytes(_contentDatKey).length > 0);
require (bytes(_metadataDatKey).length > 0);
require (stakedContentIndex[_stakeId] > 0);
// Increment totalContentHosts
totalContentHosts++;
// Generate contentId
bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId));
ContentHost storage _contentHost = contentHosts[totalContentHosts];
// Make sure the node doesn't host the same content twice
require (_contentHost.host == address(0));
_contentHost.contentHostId = _contentHostId;
_contentHost.stakeId = _stakeId;
_contentHost.host = _host;
_contentHost.encChallenge = _encChallenge;
_contentHost.contentDatKey = _contentDatKey;
_contentHost.metadataDatKey = _metadataDatKey;
contentHostIndex[_contentHostId] = totalContentHosts;
emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey);
}
/**
* @dev actual staking the content
* @param _stakeOwner the address that stake the content
* @param _contentId The ID of the content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return the newly created staked content ID
*/
function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) {
// Increment totalStakedContents
totalStakedContents++;
// Generate stakeId
bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId));
StakedContent storage _stakedContent = stakedContents[totalStakedContents];
// Make sure the node doesn't stake the same content twice
require (_stakedContent.stakeOwner == address(0));
_stakedContent.stakeId = _stakeId;
_stakedContent.contentId = _contentId;
_stakedContent.stakeOwner = _stakeOwner;
_stakedContent.profitPercentage = _profitPercentage;
_stakedContent.active = true;
_stakedContent.createdOnTimestamp = now;
stakedContentIndex[_stakeId] = totalStakedContents;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
_stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _primordialAmount;
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp);
return _stakedContent.stakeId;
}
/**
* @dev Get setting variables
* @return contentUsageType_aoContent Content Usage Type = AO Content
* @return contentUsageType_creativeCommons Content Usage Type = Creative Commons
* @return contentUsageType_taoContent Content Usage Type = T(AO) Content
* @return taoContentState_submitted TAO Content State = Submitted
* @return taoContentState_pendingReview TAO Content State = Pending Review
* @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO
*/
function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {
(,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent');
(,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons');
(,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent');
(,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted');
(,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview');
(,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO');
return (
contentUsageType_aoContent,
contentUsageType_creativeCommons,
contentUsageType_taoContent,
taoContentState_submitted,
taoContentState_pendingReview,
taoContentState_acceptedToTAO
);
}
/**
* @dev Check whether or not the content is of AO Content Usage Type
* @param _contentId The ID of the content
* @return true if yes. false otherwise
*/
function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) {
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent;
}
}
/**
* @title Name
*/
contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
contract Logos is TAOCurrency {
NameTAOPosition internal _nameTAOPosition;
// Mapping of a Name ID to the amount of Logos positioned by others to itself
// address is the address of nameId, not the eth public address
mapping (address => uint256) public positionFromOthers;
// Mapping of Name ID to other Name ID and the amount of Logos positioned by itself
mapping (address => mapping(address => uint256)) public positionToOthers;
// Mapping of a Name ID to the total amount of Logos positioned by itself to others
mapping (address => uint256) public totalPositionToOthers;
// Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned
mapping (address => mapping(address => uint256)) public advocatedTAOLogos;
// Mapping of a Name ID to the total amount of Logos earned from advocated TAO
mapping (address => uint256) public totalAdvocatedTAOLogos;
// Event broadcasted to public when `from` address position `value` Logos to `to`
event PositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `from` address unposition `value` Logos from `to`
event UnpositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId`
event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount);
// Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId`
event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of _id
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get the total sum of Logos for an address
* @param _target The address to check
* @return The total sum of Logos (own + positioned + advocated TAOs)
*/
function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) {
return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]);
}
/**
* @dev `_from` Name position `_value` Logos onto `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to position
* @return true on success
*/
function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't position Logos to itself
require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position
require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value);
positionFromOthers[_to] = positionFromOthers[_to].add(_value);
emit PositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance);
return true;
}
/**
* @dev `_from` Name unposition `_value` Logos from `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to unposition
* @return true on success
*/
function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't unposition Logos to itself
require (positionToOthers[_from][_to] >= _value);
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value);
positionFromOthers[_to] = positionFromOthers[_to].sub(_value);
emit UnpositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance);
return true;
}
/**
* @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate
* @param _taoId The ID of the advocated TAO
* @param _amount the amount to reward
* @return true on success
*/
function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) {
require (_amount > 0);
address _nameId = _nameTAOPosition.getAdvocate(_taoId);
advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount);
emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount);
return true;
}
/**
* @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId`
* @param _fromNameId The ID of the Name that sends the Logos
* @param _toNameId The ID of the Name that receives the Logos
* @param _taoId The ID of the advocated TAO
* @return true on success
*/
function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) {
require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId));
require (advocatedTAOLogos[_fromNameId][_taoId] > 0);
require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]);
uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId];
advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount);
totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount);
advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount);
emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount);
return true;
}
}
/**
* @title AOLibrary
*/
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000
/**
* @dev Check whether or not the given TAO ID is a TAO
* @param _taoId The ID of the TAO
* @return true if yes. false otherwise
*/
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0);
}
/**
* @dev Check whether or not the given Name ID is a Name
* @param _nameId The ID of the Name
* @return true if yes. false otherwise
*/
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1);
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
* @param _sender The address to check
* @param _theAO The AO address
* @param _nameTAOPositionAddress The address of NameTAOPosition
* @return true if yes, false otherwise
*/
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
/**
* @dev Return the divisor used to correctly calculate percentage.
* Percentage stored throughout AO contracts covers 4 decimals,
* so 1% is 10000, 1.25% is 12500, etc
*/
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
/**
* @dev Return the divisor used to correctly calculate multiplier.
* Multiplier stored throughout AO contracts covers 6 decimals,
* so 1 is 1000000, 0.023 is 23000, etc
*/
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
/**
* @dev Check whether or not content creator can stake a content based on the provided params
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return true if yes. false otherwise
*/
function canStake(address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage) public view returns (bool) {
return (
bytes(_baseChallenge).length > 0 &&
bytes(_encChallenge).length > 0 &&
bytes(_contentDatKey).length > 0 &&
bytes(_metadataDatKey).length > 0 &&
_fileSize > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) &&
_stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true &&
_profitPercentage <= _PERCENTAGE_DIVISOR
);
}
/**
* @dev Check whether or the requested unstake amount is valid
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @param _stakedNetworkAmount The current staked network token amount
* @param _stakedPrimordialAmount The current staked primordial token amount
* @param _stakedFileSize The file size of the staked content
* @return true if can unstake, false otherwise
*/
function canUnstakePartial(
address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
uint256 _stakedNetworkAmount,
uint256 _stakedPrimordialAmount,
uint256 _stakedFileSize) public view returns (bool) {
if (
(_denomination.length > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0) &&
_stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)
) ||
_stakedPrimordialAmount < _primordialAmount ||
(
_denomination.length > 0
&& (_networkIntegerAmount > 0 || _networkFractionAmount > 0)
&& (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize)
) ||
( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize)
) {
return false;
} else {
return true;
}
}
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _isAOContentUsageType whether or not the content is of AO Content usage type
* @param _fileSize The size of the file
* @param _stakedAmount The total staked amount
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @return true when the amount is sufficient, false otherwise
*/
function canStakeExisting(
address _treasuryAddress,
bool _isAOContentUsageType,
uint256 _fileSize,
uint256 _stakedAmount,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount
) public view returns (bool) {
if (_isAOContentUsageType) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize;
} else {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize;
}
}
/**
* @dev Check whether the network token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _price The price of the content
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @return true when the amount is sufficient, false otherwise
*/
function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price;
}
/**
* @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _currentPrimordialBalance Account's current primordial token balance
* @param _additionalWeightedMultiplier The weighted multiplier to be added
* @param _additionalPrimordialAmount The primordial token amount to be added
* @return the new primordial weighted multiplier
*/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedTokens.div(_totalTokens);
} else {
return _additionalWeightedMultiplier;
}
}
/**
* @dev Return the address that signed the message when a node wants to become a host
* @param _callingContractAddress the address of the calling contract
* @param _message the message that was signed
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the address that signed the TAO content state update
* @param _callingContractAddress the address of the calling contract
* @param _contentId the ID of the content
* @param _taoId the ID of the TAO
* @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the staking and earning information of a stake ID
* @param _contentAddress The address of AOContent
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId);
(uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier,
totalStakeEarning,
totalHostEarning,
totalTheAOEarning
);
}
/**
* @dev Return the staking information of a stake ID
* @param _contentAddress The address of AOContent
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
*/
function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
(,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier
);
}
/**
* @dev Return the earning information of a stake ID
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
return (
AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId)
);
}
/**
* @dev Calculate the primordial token multiplier on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Multiplier = S
* Ending Multiplier = E
* To Purchase = P
* Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting multiplier in (10 ** 6)
* @param _endingMultiplier The ending multiplier in (10 ** 6)
* @return The multiplier in (10 ** 6)
*/
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* Multiplier = (1 - (temp / T)) x (S-E)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals
* so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E)
* Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR
* Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR
* Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation
* Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)
*/
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
/**
* Since _startingMultiplier and _endingMultiplier are in 6 decimals
* Need to divide multiplier by _MULTIPLIER_DIVISOR
*/
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
/**
* @dev Calculate the bonus percentage of network token on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Network Token Bonus Multiplier = Bs
* Ending Network Token Bonus Multiplier = Be
* To Purchase = P
* AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* B% = (1 - (temp / T)) x (Bs-Be)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals
* so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be)
* B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)
* But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR
*/
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
/**
* @dev Calculate the bonus amount of network token on a given lot
* AO Bonus Amount = B% x P
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network token bonus amount
*/
uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkTokenBonus;
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _maximumMultiplier = S
* _amountToBurn = B
* B = ((S x P) - (P x M)) / S
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _maximumMultiplier The maximum multiplier of this account
* @return The maximum burn amount
*/
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
/**
* @dev Calculate the new multiplier after burning primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToBurn = B
* _newMultiplier = E
* E = (P x M) / (P - B)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier
*/
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
/**
* @dev Calculate the new multiplier after converting network token to primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToConvert = C
* _newMultiplier = E
* E = (P x M) / (P + C)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier
*/
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
/**
* @dev Get TAO Currency Balances given a nameId
* @param _nameId The ID of the Name
* @param _logosAddress The address of Logos
* @param _ethosAddress The address of Ethos
* @param _pathosAddress The address of Pathos
* @return sum Logos balance of the Name ID
* @return Ethos balance of the Name ID
* @return Pathos balance of the Name ID
*/
function getTAOCurrencyBalances(
address _nameId,
address _logosAddress,
address _ethosAddress,
address _pathosAddress
) public view returns (uint256, uint256, uint256) {
return (
Logos(_logosAddress).sumBalanceOf(_nameId),
TAOCurrency(_ethosAddress).balanceOf(_nameId),
TAOCurrency(_pathosAddress).balanceOf(_nameId)
);
}
/**
* @dev Return the address that signed the data and nonce when validating signature
* @param _callingContractAddress the address of the calling contract
* @param _data the data that was signed
* @param _nonce The signed uint256 nonce
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce));
return ecrecover(_hash, _v, _r, _s);
}
/***** Internal Methods *****/
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for the filesize
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _fileSize The size of the file
* @return true when the amount is sufficient, false otherwise
*/
function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize;
}
}
contract Epiphany is TheAO {
string public what;
string public when;
string public why;
string public who;
address public where;
string public aSign;
string public logos;
constructor() public {
what = 'The AO';
when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.';
why = 'To Hear, See, and Speak the Human inside Humanity.';
who = 'You. Set the world, Free. – Truth';
aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf';
logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32';
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev Set `where` value
* @param _where The new value to be set
*/
function setWhere(address _where) public onlyTheAO {
where = _where;
}
} | Get setting variables return startingPrimordialMultiplier The starting multiplier used to calculate primordial token return endingPrimordialMultiplier The ending multiplier used to calculate primordial token return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus/ | function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier');
(uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier);
}
| 10,007,342 |
pragma solidity ^0.4.25;
// Non-Confidential Multiparty Registered eDelivery
contract ConfidentialMultipartyRegisteredEDelivery {
// Possible states
enum State {notexists, cancelled, finished }
struct ReceiverState{
bytes32 receiverSignature; // hB
bytes32 keySignature; // k'T
State state;
}
struct Message{
bool messageExists;
// Parties involved in the message
address sender;
address[] receivers;
mapping(address => ReceiverState) receiversState;
}
// Mapping of all messages
mapping(address => mapping(uint => Message)) messages;
// Parties involved
address public ttp;
// Constructor funcion
constructor () public {
ttp = msg.sender;
}
// finish() lets TTP finish the delivery
function finish(uint _id, address _sender, address _receiver, bytes32 _receiverSignature, bytes32 _keySignature) public {
require (msg.sender==ttp, "Only TTP can finish");
if (messages[_sender][_id].receiversState[_receiver].state==State.notexists) {
// Receiver state is 'not exists'
addReceiver(_id, _sender, _receiver, _receiverSignature, _keySignature, State.finished);
}
}
// cancel() lets sender cancel the delivery
function cancel(uint _id, address[] _receivers) public {
for (uint i = 0; i<_receivers.length;i++){
address receiverToCancel = _receivers[i];
if (messages[msg.sender][_id].receiversState[receiverToCancel].state==State.notexists) {
// Receiver state is 'not exists'
addReceiver(_id, msg.sender, receiverToCancel, 0, 0, State.cancelled);
}
}
}
// Adds a new receiver to that message
function addReceiver(uint _id, address _sender, address _receiver, bytes32 _receiverSignature, bytes32 _keySignature, State _state) private {
if (!messages[msg.sender][_id].messageExists) {
// Message not exists
messages[_sender][_id].sender = _sender;
messages[_sender][_id].messageExists = true;
}
messages[_sender][_id].receivers.push(_receiver);
messages[_sender][_id].receiversState[_receiver].receiverSignature = _receiverSignature;
messages[_sender][_id].receiversState[_receiver].keySignature = _keySignature;
messages[_sender][_id].receiversState[_receiver].state = _state;
}
// getState() returns the state of a receiver in an string format
function getState(uint _id, address _sender, address _receiver) public view returns (string) {
if (messages[_sender][_id].receiversState[_receiver].state==State.notexists) {
return "not exists";
} else if (messages[_sender][_id].receiversState[_receiver].state==State.cancelled) {
return "cancelled";
} else if (messages[_sender][_id].receiversState[_receiver].state==State.finished) {
return "finished";
}
}
// getReceiverSignature() returns the signature of a receiver
function getReceiverSignature(uint _id, address _sender, address _receiver) public view returns (bytes32) {
return messages[_sender][_id].receiversState[_receiver].receiverSignature;
}
// getKeySignature() returns the key for a receiver
function getKeySignature(uint _id, address _sender, address _receiver) public view returns (bytes32) {
return messages[_sender][_id].receiversState[_receiver].keySignature;
}
} | cancel() lets sender cancel the delivery Receiver state is 'not exists' | function cancel(uint _id, address[] _receivers) public {
for (uint i = 0; i<_receivers.length;i++){
address receiverToCancel = _receivers[i];
if (messages[msg.sender][_id].receiversState[receiverToCancel].state==State.notexists) {
addReceiver(_id, msg.sender, receiverToCancel, 0, 0, State.cancelled);
}
}
}
| 6,346,866 |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/Gauge.sol";
import "./interfaces/ICurve3Pool.sol";
import "../../uniswap/interfaces/IUniswapV2Router02.sol";
import "../../hardworkInterface/IStrategy.sol";
import "../../hardworkInterface/IVault.sol";
import "../../Controllable.sol";
import "../RewardTokenProfitNotifier.sol";
contract CRVStrategy3Pool is IStrategy, RewardTokenProfitNotifier {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
event Liquidating(uint256 amount);
event ProfitsNotCollected();
// 3CRV
address public underlying;
address public pool;
address public mintr;
address public crv;
address public curve;
address public weth;
address public dai;
address public uni;
// these tokens cannot be claimed by the governance
mapping(address => bool) public unsalvagableTokens;
address public vault;
uint256 maxUint = uint256(~0);
address[] public uniswap_CRV2DAI;
// a flag for disabling selling for simplified emergency exit
bool public sell = true;
// minimum CRV amount to be liquidation
uint256 public sellFloor = 1e18;
modifier restricted() {
require(msg.sender == vault || msg.sender == controller()
|| msg.sender == governance(),
"The sender has to be the controller, governance, or vault");
_;
}
constructor(
address _storage,
address _vault,
address _underlying,
address _gauge,
address _mintr,
address _crv,
address _curve,
address _weth,
address _dai,
address _uniswap
)
RewardTokenProfitNotifier(_storage, _crv) public {
require(IVault(_vault).underlying() == _underlying, "vault does not support 3crv");
vault = _vault;
underlying = _underlying;
pool = _gauge;
mintr = _mintr;
crv = _crv;
curve = _curve;
weth = _weth;
dai = _dai;
uni = _uniswap;
uniswap_CRV2DAI = [crv, weth, dai];
// set these tokens to be not salvageable
unsalvagableTokens[underlying] = true;
unsalvagableTokens[crv] = true;
}
function depositArbCheck() public view returns(bool) {
return true;
}
/**
* Salvages a token. We should not be able to salvage CRV and 3CRV (underlying).
*/
function salvage(address recipient, address token, uint256 amount) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
}
/**
* Withdraws 3CRV from the investment pool that mints crops.
*/
function withdraw3CrvFromPool(uint256 amount) internal {
Gauge(pool).withdraw(
Math.min(Gauge(pool).balanceOf(address(this)), amount)
);
}
/**
* Withdraws the 3CRV tokens to the pool in the specified amount.
*/
function withdrawToVault(uint256 amountUnderlying) external restricted {
withdraw3CrvFromPool(amountUnderlying);
if (IERC20(underlying).balanceOf(address(this)) < amountUnderlying) {
claimAndLiquidateCrv();
}
uint256 toTransfer = Math.min(IERC20(underlying).balanceOf(address(this)), amountUnderlying);
IERC20(underlying).safeTransfer(vault, toTransfer);
}
/**
* Withdraws all the 3CRV tokens to the pool.
*/
function withdrawAllToVault() external restricted {
claimAndLiquidateCrv();
withdraw3CrvFromPool(maxUint);
uint256 balance = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, balance);
}
/**
* Invests all the underlying 3CRV into the pool that mints crops (CRV).
*/
function investAllUnderlying() public restricted {
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(pool, 0);
IERC20(underlying).safeApprove(pool, underlyingBalance);
Gauge(pool).deposit(underlyingBalance);
}
}
/**
* Claims the CRV crop, converts it to DAI on Uniswap, and then uses DAI to mint 3CRV using the
* Curve protocol.
*/
function claimAndLiquidateCrv() internal {
if (!sell) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected();
return;
}
Mintr(mintr).mint(pool);
uint256 rewardBalance = IERC20(crv).balanceOf(address(this));
if (rewardBalance < sellFloor) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected();
return;
}
notifyProfitInRewardToken(rewardBalance);
uint256 crvBalance = IERC20(crv).balanceOf(address(this));
if (crvBalance > 0) {
emit Liquidating(crvBalance);
IERC20(crv).safeApprove(uni, 0);
IERC20(crv).safeApprove(uni, crvBalance);
// we can accept 1 as the minimum because this will be called only by a trusted worker
IUniswapV2Router02(uni).swapExactTokensForTokens(
crvBalance, 1, uniswap_CRV2DAI, address(this), block.timestamp
);
if(IERC20(dai).balanceOf(address(this)) > 0) {
curve3PoolFromDai();
}
}
}
/**
* Claims and liquidates CRV into 3CRV, and then invests all underlying.
*/
function doHardWork() public restricted {
claimAndLiquidateCrv();
investAllUnderlying();
}
/**
* Investing all underlying.
*/
function investedUnderlyingBalance() public view returns (uint256) {
return Gauge(pool).balanceOf(address(this)).add(
IERC20(underlying).balanceOf(address(this))
);
}
/**
* Uses the Curve protocol to convert the underlying asset into the mixed token.
*/
function curve3PoolFromDai() public {
uint256 daiBalance = IERC20(dai).balanceOf(address(this));
if (daiBalance > 0) {
IERC20(dai).safeApprove(curve, 0);
IERC20(dai).safeApprove(curve, daiBalance);
uint256 minimum = 0;
ICurve3Pool(curve).add_liquidity([daiBalance, 0, 0], minimum);
}
}
/**
* Can completely disable claiming CRV rewards and selling. Good for emergency withdraw in the
* simplest possible way.
*/
function setSell(bool s) public onlyGovernance {
sell = s;
}
/**
* Sets the minimum amount of CRV needed to trigger a sale.
*/
function setSellFloor(uint256 floor) public onlyGovernance {
sellFloor = floor;
}
}
| Uses the Curve protocol to convert the underlying asset into the mixed token./ | function curve3PoolFromDai() public {
uint256 daiBalance = IERC20(dai).balanceOf(address(this));
if (daiBalance > 0) {
IERC20(dai).safeApprove(curve, 0);
IERC20(dai).safeApprove(curve, daiBalance);
uint256 minimum = 0;
ICurve3Pool(curve).add_liquidity([daiBalance, 0, 0], minimum);
}
}
| 1,761,356 |
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// Dependency 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);
}
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/contracts/utils/Address.sol
// pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/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");
}
}
}
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: contracts/common/Initializable.sol
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol
// Added public isInitialized() view of private initialized bool.
// pragma solidity 0.6.10;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
/**
* @dev Return true if and only if the contract has been initialized
* @return whether the contract has been initialized
*/
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// Dependency file: contracts/common/UpgradeableClaimable.sol
// pragma solidity 0.6.10;
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {Initializable} from "contracts/common/Initializable.sol";
/**
* @title UpgradeableClaimable
* @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. Since
* this contract combines Claimable and UpgradableOwnable contracts, ownership
* can be later change via 2 step method {transferOwnership} and {claimOwnership}
*
* 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 UpgradeableClaimable is Initializable, Context {
address private _owner;
address private _pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting a custom initial owner of choice.
* @param __owner Initial owner of contract to be set.
*/
function initialize(address __owner) internal initializer {
_owner = __owner;
emit OwnershipTransferred(address(0), __owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view returns (address) {
return _pendingOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(_owner, _pendingOwner);
_owner = _pendingOwner;
_pendingOwner = address(0);
}
}
// Dependency file: contracts/truefi2/interface/ITrueStrategy.sol
// pragma solidity 0.6.10;
interface ITrueStrategy {
/**
* @dev put `amount` of tokens into the strategy
* As a result of the deposit value of the strategy should increase by at least 98% of amount
*/
function deposit(uint256 amount) external;
/**
* @dev pull at least `minAmount` of tokens from strategy and transfer to the pool
*/
function withdraw(uint256 minAmount) external;
/**
* @dev withdraw everything from strategy
* As a result of calling withdrawAll(),at least 98% of strategy's value should be transferred to the pool
* Value must become 0
*/
function withdrawAll() external;
/// @dev value evaluated to Pool's tokens
function value() external view returns (uint256);
}
// Dependency file: contracts/truefi/interface/IYToken.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IYToken is IERC20 {
function getPricePerFullShare() external view returns (uint256);
}
// Dependency file: contracts/truefi/interface/ICurve.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {IYToken} from "contracts/truefi/interface/IYToken.sol";
interface ICurve {
function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
}
interface ICurveGauge {
function balanceOf(address depositor) external view returns (uint256);
function minter() external returns (ICurveMinter);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
}
interface ICurveMinter {
function mint(address gauge) external;
function token() external view returns (IERC20);
}
interface ICurvePool {
function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount,
bool donate_dust
) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function token() external view returns (IERC20);
function curve() external view returns (ICurve);
function coins(int128 id) external view returns (IYToken);
}
// Dependency file: contracts/truefi/interface/ICrvPriceOracle.sol
// pragma solidity 0.6.10;
interface ICrvPriceOracle {
function usdToCrv(uint256 amount) external view returns (uint256);
function crvToUsd(uint256 amount) external view returns (uint256);
}
// Dependency file: contracts/truefi/interface/IUniswapRouter.sol
// pragma solidity 0.6.10;
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// Dependency file: contracts/common/UpgradeableERC20.sol
// pragma solidity 0.6.10;
// import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {Initializable} from "contracts/common/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_initialize(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public virtual view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public virtual override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function updateNameAndSymbol(string memory __name, string memory __symbol) internal {
_name = __name;
_symbol = __symbol;
}
}
// Dependency file: contracts/truefi2/interface/ILoanToken2.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {ERC20} from "contracts/common/UpgradeableERC20.sol";
// import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol";
interface ILoanToken2 is IERC20 {
enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated}
function borrower() external view returns (address);
function amount() external view returns (uint256);
function term() external view returns (uint256);
function apy() external view returns (uint256);
function start() external view returns (uint256);
function lender() external view returns (address);
function debt() external view returns (uint256);
function pool() external view returns (ITrueFiPool2);
function profit() external view returns (uint256);
function status() external view returns (Status);
function getParameters()
external
view
returns (
uint256,
uint256,
uint256
);
function fund() external;
function withdraw(address _beneficiary) external;
function settle() external;
function enterDefault() external;
function liquidate() external;
function redeem(uint256 _amount) external;
function repay(address _sender, uint256 _amount) external;
function repayInFull(address _sender) external;
function reclaim() external;
function allowTransfer(address account, bool _status) external;
function repaid() external view returns (uint256);
function isRepaid() external view returns (bool);
function balance() external view returns (uint256);
function value(uint256 _balance) external view returns (uint256);
function token() external view returns (ERC20);
function version() external pure returns (uint8);
}
//interface IContractWithPool {
// function pool() external view returns (ITrueFiPool2);
//}
//
//// Had to be split because of multiple inheritance problem
//interface ILoanToken2 is ILoanToken, IContractWithPool {
//
//}
// Dependency file: contracts/truefi2/interface/ITrueLender2.sol
// pragma solidity 0.6.10;
// import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol";
// import {ILoanToken2} from "contracts/truefi2/interface/ILoanToken2.sol";
interface ITrueLender2 {
// @dev calculate overall value of the pools
function value(ITrueFiPool2 pool) external view returns (uint256);
// @dev distribute a basket of tokens for exiting user
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
function transferAllLoanTokens(ILoanToken2 loan, address recipient) external;
}
// Dependency file: contracts/truefi2/interface/IERC20WithDecimals.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20WithDecimals is IERC20 {
function decimals() external view returns (uint256);
}
// Dependency file: contracts/truefi2/interface/ITrueFiPoolOracle.sol
// pragma solidity 0.6.10;
// import {IERC20WithDecimals} from "contracts/truefi2/interface/IERC20WithDecimals.sol";
/**
* @dev Oracle that converts any token to and from TRU
* Used for liquidations and valuing of liquidated TRU in the pool
*/
interface ITrueFiPoolOracle {
// token address
function token() external view returns (IERC20WithDecimals);
// amount of tokens 1 TRU is worth
function truToToken(uint256 truAmount) external view returns (uint256);
// amount of TRU 1 token is worth
function tokenToTru(uint256 tokenAmount) external view returns (uint256);
// USD price of token with 18 decimals
function tokenToUsd(uint256 tokenAmount) external view returns (uint256);
}
// Dependency file: contracts/truefi2/interface/I1Inch3.sol
// pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
interface I1Inch3 {
struct SwapDescription {
address srcToken;
address dstToken;
address srcReceiver;
address dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
function swap(
address caller,
SwapDescription calldata desc,
bytes calldata data
)
external
returns (
uint256 returnAmount,
uint256 gasLeft,
uint256 chiSpent
);
function unoswap(
address srcToken,
uint256 amount,
uint256 minReturn,
bytes32[] calldata /* pools */
) external payable returns (uint256 returnAmount);
}
// Dependency file: contracts/truefi2/interface/ISAFU.sol
// pragma solidity 0.6.10;
interface ISAFU {
function poolDeficit(address pool) external view returns (uint256);
}
// Dependency file: contracts/truefi2/interface/ITrueFiPool2.sol
// pragma solidity 0.6.10;
// import {ERC20, IERC20} from "contracts/common/UpgradeableERC20.sol";
// import {ITrueLender2, ILoanToken2} from "contracts/truefi2/interface/ITrueLender2.sol";
// import {ITrueFiPoolOracle} from "contracts/truefi2/interface/ITrueFiPoolOracle.sol";
// import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol";
// import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol";
interface ITrueFiPool2 is IERC20 {
function initialize(
ERC20 _token,
ERC20 _stakingToken,
ITrueLender2 _lender,
I1Inch3 __1Inch,
ISAFU safu,
address __owner
) external;
function token() external view returns (ERC20);
function oracle() external view returns (ITrueFiPoolOracle);
/**
* @dev Join the pool by depositing tokens
* @param amount amount of tokens to deposit
*/
function join(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount) external;
/**
* @dev pay borrowed money back to pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 currencyAmount) external;
/**
* @dev SAFU buys LoanTokens from the pool
*/
function liquidate(ILoanToken2 loan) external;
}
// Dependency file: contracts/truefi2/libraries/OneInchExchange.sol
// pragma solidity 0.6.10;
// pragma experimental ABIEncoderV2;
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol";
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
interface IUniRouter {
function token0() external view returns (address);
function token1() external view returns (address);
}
library OneInchExchange {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
uint256 constant REVERSE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000;
event Swapped(I1Inch3.SwapDescription description, uint256 returnedAmount);
/**
* @dev Forward data to 1Inch contract
* @param _1inchExchange address of 1Inch (currently 0x11111112542d85b3ef69ae05771c2dccff4faa26 for mainnet)
* @param data Data that is forwarded into the 1inch exchange contract. Can be acquired from 1Inch API https://api.1inch.exchange/v3.0/1/swap
* [See more](https://docs.1inch.exchange/api/quote-swap#swap)
*
* @return description - description of the swap
*/
function exchange(I1Inch3 _1inchExchange, bytes calldata data)
internal
returns (I1Inch3.SwapDescription memory description, uint256 returnedAmount)
{
if (data[0] == 0x7c) {
// call `swap()`
(, description, ) = abi.decode(data[4:], (address, I1Inch3.SwapDescription, bytes));
} else {
// call `unoswap()`
(address srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pathData) = abi.decode(
data[4:],
(address, uint256, uint256, bytes32[])
);
description.srcToken = srcToken;
description.amount = amount;
description.minReturnAmount = minReturn;
description.flags = 0;
uint256 lastPath = uint256(pathData[pathData.length - 1]);
IUniRouter uniRouter = IUniRouter(address(lastPath & ADDRESS_MASK));
bool isReverse = lastPath & REVERSE_MASK > 0;
description.dstToken = isReverse ? uniRouter.token0() : uniRouter.token1();
description.dstReceiver = address(this);
}
IERC20(description.srcToken).safeApprove(address(_1inchExchange), description.amount);
uint256 balanceBefore = IERC20(description.dstToken).balanceOf(description.dstReceiver);
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(_1inchExchange).call(data);
if (!success) {
// Revert with original error message
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
uint256 balanceAfter = IERC20(description.dstToken).balanceOf(description.dstReceiver);
returnedAmount = balanceAfter.sub(balanceBefore);
emit Swapped(description, returnedAmount);
}
}
// Root file: contracts/truefi2/strategies/CurveYearnStrategy.sol
pragma solidity 0.6.10;
// pragma experimental ABIEncoderV2;
// import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {UpgradeableClaimable} from "contracts/common/UpgradeableClaimable.sol";
// import {ITrueStrategy} from "contracts/truefi2/interface/ITrueStrategy.sol";
// import {ICurveGauge, ICurveMinter, ICurvePool, IERC20} from "contracts/truefi/interface/ICurve.sol";
// import {ICrvPriceOracle} from "contracts/truefi/interface/ICrvPriceOracle.sol";
// import {IUniswapRouter} from "contracts/truefi/interface/IUniswapRouter.sol";
// import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol";
// import {I1Inch3} from "contracts/truefi2/interface/I1Inch3.sol";
// import {OneInchExchange} from "contracts/truefi2/libraries/OneInchExchange.sol";
// import {IERC20WithDecimals} from "contracts/truefi2/interface/IERC20WithDecimals.sol";
/**
* @dev TrueFi pool strategy that allows depositing stablecoins into Curve Yearn pool (0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51)
* Supports DAI, USDC, USDT and TUSD
* Curve LP tokens are being deposited into Curve Gauge and CRV rewards can be sold on 1Inch exchange and transferred to the pool
*/
contract CurveYearnStrategy is UpgradeableClaimable, ITrueStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for IERC20WithDecimals;
using OneInchExchange for I1Inch3;
// Number of tokens in Curve yPool
uint8 public constant N_TOKENS = 4;
// Max slippage during the swap
uint256 public constant MAX_PRICE_SLIPPAGE = 200; // 2%
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
// Index of token in Curve pool
// 0 - DAI
// 1 - USDC
// 2 - USDT
// 3 - TUSD
uint8 public tokenIndex;
ICurvePool public curvePool;
ICurveGauge public curveGauge;
ICurveMinter public minter;
I1Inch3 public _1Inch;
IERC20WithDecimals public token;
address public pool;
// CRV price oracle
ICrvPriceOracle public crvOracle;
// ======= STORAGE DECLARATION END ===========
event OracleChanged(ICrvPriceOracle newOracle);
event Deposited(uint256 depositedAmount, uint256 receivedYAmount);
event Withdrawn(uint256 minAmount, uint256 yAmount);
event WithdrawnAll(uint256 yAmount);
modifier onlyPool() {
require(msg.sender == pool, "CurveYearnStrategy: Can only be called by pool");
_;
}
function initialize(
ITrueFiPool2 _pool,
ICurvePool _curvePool,
ICurveGauge _curveGauge,
ICurveMinter _minter,
I1Inch3 _1inchExchange,
ICrvPriceOracle _crvOracle,
uint8 _tokenIndex
) external initializer {
UpgradeableClaimable.initialize(msg.sender);
token = IERC20WithDecimals(address(_pool.token()));
pool = address(_pool);
curvePool = _curvePool;
curveGauge = _curveGauge;
minter = _minter;
_1Inch = _1inchExchange;
crvOracle = _crvOracle;
tokenIndex = _tokenIndex;
}
/**
* @dev Sets new crv oracle address
* @param _crvOracle new oracle address
*/
function setOracle(ICrvPriceOracle _crvOracle) external onlyOwner {
crvOracle = _crvOracle;
emit OracleChanged(_crvOracle);
}
/**
* @dev Transfer `amount` of `token` from pool and add it as
* liquidity to the Curve yEarn Pool
* Curve LP tokens are deposited into Curve Gauge
* @param amount amount of token to add to curve
*/
function deposit(uint256 amount) external override onlyPool {
token.safeTransferFrom(pool, address(this), amount);
uint256 totalAmount = token.balanceOf(address(this));
uint256[N_TOKENS] memory amounts = [uint256(0), 0, 0, 0];
amounts[tokenIndex] = totalAmount;
token.safeApprove(address(curvePool), totalAmount);
uint256 conservativeMinAmount = calcTokenAmount(totalAmount).mul(999).div(1000);
curvePool.add_liquidity(amounts, conservativeMinAmount);
// stake yCurve tokens in gauge
uint256 yBalance = curvePool.token().balanceOf(address(this));
curvePool.token().safeApprove(address(curveGauge), yBalance);
curveGauge.deposit(yBalance);
emit Deposited(amount, yBalance);
}
/**
* @dev pull at least `minAmount` of tokens from strategy
* Remove token liquidity from curve and transfer to pool
* @param minAmount Minimum amount of tokens to remove from strategy
*/
function withdraw(uint256 minAmount) external override onlyPool {
// get rough estimate of how much yCRV we should sell
uint256 roughCurveTokenAmount = calcTokenAmount(minAmount);
uint256 yBalance = yTokenBalance();
require(roughCurveTokenAmount <= yBalance, "CurveYearnStrategy: Not enough Curve liquidity tokens in pool to cover borrow");
// Try to withdraw a bit more to be safe, but not above the total balance
uint256 conservativeCurveTokenAmount = min(yBalance, roughCurveTokenAmount.mul(1005).div(1000));
// pull tokens from gauge
withdrawFromGaugeIfNecessary(conservativeCurveTokenAmount);
// remove TUSD from curve
curvePool.token().safeApprove(address(curvePool), conservativeCurveTokenAmount);
curvePool.remove_liquidity_one_coin(conservativeCurveTokenAmount, tokenIndex, minAmount, false);
transferAllToPool();
emit Withdrawn(minAmount, conservativeCurveTokenAmount);
}
/**
*@dev withdraw everything from strategy
* Use with caution because Curve slippage is not controlled
*/
function withdrawAll() external override onlyPool {
curveGauge.withdraw(curveGauge.balanceOf(address(this)));
uint256 yBalance = yTokenBalance();
curvePool.token().safeApprove(address(curvePool), yBalance);
curvePool.remove_liquidity_one_coin(yBalance, tokenIndex, 0, false);
transferAllToPool();
emit WithdrawnAll(yBalance);
}
/**
* @dev Total pool value in USD
* @notice Balance of CRV is not included into value of strategy,
* because it cannot be converted to pool tokens automatically
* @return Value of pool in USD
*/
function value() external override view returns (uint256) {
return yTokenValue();
}
/**
* @dev Price of in USD
* @return Oracle price of TRU in USD
*/
function yTokenValue() public view returns (uint256) {
return normalizeDecimals(yTokenBalance().mul(curvePool.curve().get_virtual_price()).div(1 ether));
}
/**
* @dev Get total balance of curve.fi pool tokens
* @return Balance of y pool tokens in this contract
*/
function yTokenBalance() public view returns (uint256) {
return curvePool.token().balanceOf(address(this)).add(curveGauge.balanceOf(address(this)));
}
/**
* @dev Price of CRV in USD
* @return Oracle price of TRU in USD
*/
function crvValue() public view returns (uint256) {
uint256 balance = crvBalance();
if (balance == 0 || address(crvOracle) == address(0)) {
return 0;
}
return normalizeDecimals(conservativePriceEstimation(crvOracle.crvToUsd(balance)));
}
/**
* @dev Get total balance of CRV tokens
* @return Balance of stake tokens in this contract
*/
function crvBalance() public view returns (uint256) {
return minter.token().balanceOf(address(this));
}
/**
* @dev Collect CRV tokens minted by staking at gauge
*/
function collectCrv() external {
minter.mint(address(curveGauge));
}
/**
* @dev Swap collected CRV on 1inch and transfer gains to the pool
* Receiver of the tokens should be the pool
* Revert if resulting exchange price is much smaller than the oracle price
* @param data Data that is forwarded into the 1inch exchange contract. Can be acquired from 1Inch API https://api.1inch.exchange/v3.0/1/swap
* [See more](https://docs.1inch.exchange/api/quote-swap#swap)
*/
function sellCrv(bytes calldata data) external {
(I1Inch3.SwapDescription memory swap, uint256 balanceDiff) = _1Inch.exchange(data);
uint256 expectedGain = normalizeDecimals(crvOracle.crvToUsd(swap.amount));
require(swap.srcToken == address(minter.token()), "CurveYearnStrategy: Source token is not CRV");
require(swap.dstToken == address(token), "CurveYearnStrategy: Destination token is not TUSD");
require(swap.dstReceiver == pool, "CurveYearnStrategy: Receiver is not pool");
require(balanceDiff >= conservativePriceEstimation(expectedGain), "CurveYearnStrategy: Not optimal exchange");
}
/**
* @dev Expected amount of minted Curve.fi yDAI/yUSDC/yUSDT/yTUSD tokens.
* @param currencyAmount amount to calculate for
* @return expected amount minted given currency amount
*/
function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) {
uint256 yTokenAmount = currencyAmount.mul(1e18).div(curvePool.coins(tokenIndex).getPricePerFullShare());
uint256[N_TOKENS] memory yAmounts = [uint256(0), 0, 0, 0];
yAmounts[tokenIndex] = yTokenAmount;
return curvePool.curve().calc_token_amount(yAmounts, true);
}
/**
* @dev ensure enough curve.fi pool tokens are available
* Check if current available amount of TUSD is enough and
* withdraw remainder from gauge
* @param neededAmount amount required
*/
function withdrawFromGaugeIfNecessary(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = curvePool.token().balanceOf(address(this));
if (currentlyAvailableAmount < neededAmount) {
curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount));
}
}
/**
* @dev Internal function to transfer entire token balance to pool
*/
function transferAllToPool() internal {
token.safeTransfer(pool, token.balanceOf(address(this)));
}
/**
* @dev Calculate price minus max percentage of slippage during exchange
* This will lead to the pool value become a bit undervalued
* compared to the oracle price but will ensure that the value doesn't drop
* when token exchanges are performed.
*/
function conservativePriceEstimation(uint256 price) internal pure returns (uint256) {
return price.mul(uint256(10000).sub(MAX_PRICE_SLIPPAGE)).div(10000);
}
/**
* @dev Helper function to calculate minimum of `a` and `b`
* @param a First variable to check if minimum
* @param b Second variable to check if minimum
* @return Lowest value between a and b
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? b : a;
}
/**
* @dev Helper function to convert between token precision
* @param _value Value to normalize decimals for
* @return Normalized value
*/
function normalizeDecimals(uint256 _value) internal view returns (uint256) {
return _value.mul(10**token.decimals()).div(10**18);
}
} | Collect CRV tokens minted by staking at gauge/ | function collectCrv() external {
minter.mint(address(curveGauge));
}
| 1,201,452 |
/**
*Submitted for verification at Etherscan.io on 2021-03-11
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
// 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;
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// 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/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: contracts/Deafbeef721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev {ERC721} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - token ID and URI autogeneration
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract Deafbeef721 is Context, AccessControl, ERC721 {
using Counters for Counters.Counter;
using SafeMath for uint256;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 public numSeries;
bool allowInternalPurchases = true; //optional internal purchasing code. Can disable to use only an external purchasing contract
struct SeriesStruct {
bytes32[10] codeLocations; //transaction hash of code location. 10 slots available
uint32 numCodeLocations; //maximum codes used in codes array
uint32[8] p; //parameters
uint256 numMint; //number minted to date
uint256 maxMint; //maximum number of model outputs
uint256 curPricePerToken; //curent token price
//TODO: additional parameters for automatically changing pricing curve
bool locked; //can't modify maxMint or codeLocation
bool paused; //paused for purchases
}
struct TokenParamsStruct {
bytes32 seed; //hash seed for random generation
//general purpose parameters for each token.
// could be parameter to the generative code
uint32[8] p; //parameters
}
mapping(uint256 => TokenParamsStruct) tokenParams; //maps each token to set of parameters
mapping(uint256 => SeriesStruct) series; //series
mapping(uint256 => uint256) token2series; //maps each token to a series
modifier requireAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Requires admin privileges");
_;
}
modifier sidInRange(uint256 sid) {
require(sid < numSeries,"Series id does not exist");
_;
}
modifier requireUnlocked(uint256 sid) {
require(!series[sid].locked);
_;
}
function setMaxMint(uint256 sid, uint256 m) public requireAdmin sidInRange(sid) requireUnlocked(sid) {
series[sid].maxMint = m;
}
function setNumCodeLocations(uint256 sid, uint32 n) public requireAdmin sidInRange(sid) requireUnlocked(sid) {
//between 1 and 10 code locations.
require(n <= 10,"Maximum 10 code locations");
require(n > 0,"Minimum 1 code locations");
series[sid].numCodeLocations = n;
}
function setCodeLocation(uint256 sid, uint256 i, bytes32 txhash) public requireAdmin sidInRange(sid) requireUnlocked(sid) {
require(i < series[sid].numCodeLocations,"Index larger than numCodeLocations");
//transaction hash of where code is stored. There are 5 slots indexed by i
//The code is UTF-8 encoded and stored in the 'input data' field of this transaction
series[sid].codeLocations[i] = txhash;
}
function setSeriesParam(uint256 sid, uint256 i, uint32 v) public requireAdmin sidInRange(sid) requireUnlocked(sid) {
require(i<8,"Parameter index must be less than 8");
//transaction hash of where code is stored.
series[sid].p[i] = v;
}
//Require MINTER role to allow token param updates.
// This will allow a separate contract with appropriate permissions
// to interface with the user, about what is allowed depending on the tokens
// NOTE: seed can never be updated.
// also, don't allow updates to p[7], which is used to track number of transfers
function setTokenParam(uint256 tokenID, uint256 i, uint32 v) public {
require(hasRole(MINTER_ROLE, _msgSender()), "Deafbeef721: must have minter role to update tokenparams");
require(tokenID < _tokenIdTracker.current(),"TokenId out of range");
require(i<7,"Parameter index must be less than 7");
tokenParams[tokenID].p[i] = v;
}
function getTokenParams(uint256 i) public view returns (bytes32 seed, bytes32 codeLocation0, uint256 seriesID, uint32 p0, uint32 p1, uint32 p2, uint32 p3, uint32 p4, uint32 p5, uint32 p6, uint32 p7) {
require(i < _tokenIdTracker.current(),"TokenId out of range");
uint256 sid = token2series[i];
codeLocation0 = series[sid].codeLocations[0];
seriesID = sid;
seed = tokenParams[i].seed;
p0 = tokenParams[i].p[0];
p1 = tokenParams[i].p[1];
p2 = tokenParams[i].p[2];
p3 = tokenParams[i].p[3];
p4 = tokenParams[i].p[4];
p5 = tokenParams[i].p[5];
p6 = tokenParams[i].p[6];
p7 = tokenParams[i].p[7];
}
function getSeriesParams(uint256 i) public view returns(uint32 p0, uint32 p1,uint32 p2, uint32 p3, uint32 p4, uint32 p5, uint32 p6, uint32 p7) {
require(i < numSeries,"Series ID out of range");
p0 = series[i].p[0];
p1 = series[i].p[1];
p2 = series[i].p[2];
p3 = series[i].p[3];
p4 = series[i].p[4];
p5 = series[i].p[5];
p6 = series[i].p[6];
p7 = series[i].p[7];
}
function getSeries(uint256 i) public view returns (bytes32 codeLocation0, uint256 numCodeLocations, uint256 numMint, uint256 maxMint, uint256 curPricePerToken, bool paused, bool locked) {
require(i < numSeries,"Series ID out of range");
codeLocation0 = series[i].codeLocations[0];
numCodeLocations = series[i].numCodeLocations;
numMint = series[i].numMint;
maxMint = series[i].maxMint;
locked = series[i].locked;
paused = series[i].paused;
curPricePerToken = series[i].curPricePerToken;
}
function getCodeLocation(uint256 sid, uint256 i) public view sidInRange(sid) returns(bytes32 txhash) {
require(i < 10,"codeLocation index out of range");
//transaction hash of where code is stored. 10 slots indexed by i
//The code is UTF-8 encoded and stored in the 'input data' field of this transaction
return series[sid].codeLocations[i];
}
function addSeries() public requireAdmin returns(uint256 sid) {
series[numSeries].maxMint = 50; //maximum number of model outputs
series[numSeries].curPricePerToken = .05e18; //curent token price
series[numSeries].numCodeLocations = 1;
series[numSeries].paused = true;
numSeries = numSeries.add(1);
return numSeries;
}
//allow MINTER role to change price. This is so an external minting contract
// perform auto price adjustment
function setPrice(uint256 sid, uint256 p) public sidInRange(sid) {
require(hasRole(MINTER_ROLE, _msgSender()), "Deafbeef721: must have minter role to change price");
series[sid].curPricePerToken = p;
}
function setAllowInternalPurchases(bool m) public requireAdmin {
allowInternalPurchases = m;
}
//pause or unpause
function setPaused(uint256 sid,bool m) public sidInRange(sid) requireAdmin {
series[sid].paused = m;
}
function lockCodeForever(uint256 sid) public sidInRange(sid) requireAdmin {
//Can no longer update max mint, code locations, or series parameters
series[sid].locked = true;
}
function withdraw(uint256 amount) public requireAdmin {
require(amount <= address(this).balance,"Insufficient funds to withdraw");
msg.sender.transfer(amount);
}
function setBaseURI(string memory baseURI) public requireAdmin {
_setBaseURI(baseURI);
}
Counters.Counter private _tokenIdTracker;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}.
*/
constructor(string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setBaseURI(baseURI);
addSeries();
}
/**
* @dev Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
//only addresses with MINTER_ROLE can mint
//this could be an admin, or from another minter contract that controls purchasing and auto price adjustment
function mint(uint256 sid, address to) public virtual returns (uint256 _tokenId) {
require(hasRole(MINTER_ROLE, _msgSender()), "Deafbeef721: must have minter role to mint");
return _mintInternal(sid,to);
}
//only accessible to contract
function _mintInternal(uint256 sid, address to) internal virtual returns (uint256 _tokenId) {
require(series[sid].numMint.add(1) <= series[sid].maxMint,"Maximum already minted");
series[sid].numMint = series[sid].numMint.add(1);
_mint(to, _tokenIdTracker.current());
uint256 tokenID = _tokenIdTracker.current();
bytes32 hash = keccak256(abi.encodePacked(tokenID,block.timestamp,block.difficulty,msg.sender));
//store random hash
tokenParams[tokenID].seed = hash;
token2series[tokenID] = sid;
_tokenIdTracker.increment();
return tokenID;
}
// Allow public purchases. This can be disabled with a flag
function purchase(uint256 sid) public sidInRange(sid) payable returns (uint256 _tokenId) {
require(allowInternalPurchases,"Can only purchase from external minting contract");
require(!series[sid].paused,"Purchasing is paused");
return purchaseTo(sid, msg.sender);
}
function purchaseTo(uint256 sid,address _to) public sidInRange(sid) payable returns(uint256 _tokenId){
require(allowInternalPurchases,"Can only purchase from external minting contract");
require(!series[sid].paused,"Purchasing is paused");
require(msg.value>=series[sid].curPricePerToken, "Must send minimum value to mint!");
//send change if too much was sent
if (msg.value > 0) {
uint256 diff = msg.value.sub(series[sid].curPricePerToken);
if (diff > 0) {
msg.sender.transfer(diff);
}
}
uint256 tokenId = _mintInternal(sid,_to);
//TODO: possibly auto adjust price
return tokenId;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
//increase a counter each time token is transferred
//this can be used as a parameter to the generative script.
tokenParams[tokenId].p[7]++;
}
} | only addresses with MINTER_ROLE can mintthis could be an admin, or from another minter contract that controls purchasing and auto price adjustment | function mint(uint256 sid, address to) public virtual returns (uint256 _tokenId) {
require(hasRole(MINTER_ROLE, _msgSender()), "Deafbeef721: must have minter role to mint");
return _mintInternal(sid,to);
}
| 7,726,246 |
./partial_match/1/0xb0849647424573358B9ECc9EA4DAb4Bb32399def/sources/contracts/testContracts/EnumerableERC1155.sol | Reduce the presale max supply of tokens for a given token id _newPresaleMaxSupply The new maximum supply of tokens available to mint _tokenId The token id to reduce the max supply for/ | function reducePresaleMaxSupply(
uint256 _tokenId,
uint256 _newPresaleMaxSupply
) external onlyOwner {
require(
tokenPresaleMaxSupply[_tokenId] == 0 ||
_newPresaleMaxSupply < tokenPresaleMaxSupply[_tokenId],
"NEW_MAX_SUPPLY_TOO_HIGH"
);
tokenPresaleMaxSupply[_tokenId] = _newPresaleMaxSupply;
}
| 2,690,668 |
./full_match/1/0x130AD7815c795De55B9FADB443cc0E4A343d0F85/sources/contracts/TokenSale.sol | Allows a user to get back his deposit in case token sale was unsuccessful./ | function claimRefund() external whenFail {
uint amount = usersDepositRaw[msg.sender];
usersDepositRaw[msg.sender] = 0;
require(sent, "Transfer failed");
}
| 8,400,934 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "./TellorStake.sol";
import "./TellorGetters.sol";
import "./Utilities.sol";
import "./ITellor.sol";
import "./SafeMath.sol";
/**
* @title Tellor Oracle System
* @dev Oracle contract where miners can submit the proof of work along with the value.
*/
contract Tellor is TellorStake {
using SafeMath for uint256;
event TipAdded(
address indexed _sender,
uint256 indexed _requestId,
uint256 _tip,
uint256 _totalTips
);
//emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system)
event NewChallenge(
bytes32 indexed _currentChallenge,
uint256[5] _currentRequestId,
uint256 _difficulty,
uint256 _totalTips
);
//Emits upon a successful Mine, indicates the blockTime at point of the mine and the value mined
event NewValue(
uint256[5] _requestId,
uint256 _time,
uint256[5] _value,
uint256 _totalTips,
bytes32 indexed _currentChallenge
);
//Emits upon each mine (5 total) and shows the miner, nonce, and value submitted
event NonceSubmitted(
address indexed _miner,
string _nonce,
uint256[5] _requestId,
uint256[5] _value,
bytes32 indexed _currentChallenge,
uint256 _slot
);
/**
* @dev allows for the deity to update the Extension contract address
* @param _ext the address of the new Extension Contract
*/
function changeExtension(address _ext) external {
require(msg.sender == addresses[_DEITY], "only deity can call this fn");
addresses[_EXTENSION] = _ext;
}
/**
* @dev allows for the deity to update the Migrator contract address
* @param _migrator the address of the new Tellor Contract
*/
function changeMigrator(address _migrator) external {
require(msg.sender == addresses[_DEITY], "only deity can call this fn");
addresses[_MIGRATOR] = _migrator;
}
/**
* @dev This is an internal function used by the function migrate that helps to
* swap old trb tokens for new ones based on the user's old Tellor balance
* @param _user is the msg.sender address of the user to migrate the balance from
*/
function _migrate(address _user) internal {
require(!migrated[_user], "Already migrated");
_doMint(_user, ITellor(addresses[_OLD_TELLOR]).balanceOf(_user));
migrated[_user] = true;
}
/**
* @dev This is an external function used by only the Migrator contract that helps to
* swap old trb tokens for new ones based on a custom amount and allows it
* to bypass the flag for an address that has already migrated. This is needed to ensure
* tokens locked on contract(pool) can be transfered to a user and also allow them to
* swap old tokens to the same address if it held any
* @param _origin is the address of the user to migrate the balance from
* @param _destination is the address that will receive tokens
* @param _amount is the amount to mint to the user
* @param _bypass is a flag used by the migrator to allow it to bypass the "migrated = true" flag
*/
function migrateFrom(
address _origin,
address _destination,
uint256 _amount,
bool _bypass
) external {
require(msg.sender == addresses[_MIGRATOR], "not allowed");
_migrateFrom(_origin, _destination, _amount, _bypass);
}
/**
* @dev This is an external function used by only the Migrator contract that helps to
* swap old trb tokens for new ones based on a custom amount
* @param _origin is an array of user addresses to migrate the balance from
* @param _destination is an array of the address that will receive tokens
* @param _amount is the amount to mint to the user
*/
function migrateFromBatch(
address[] calldata _origin,
address[] calldata _destination,
uint256[] calldata _amount
) external {
require(msg.sender == addresses[_MIGRATOR], "not allowed");
require(
_origin.length == _destination.length &&
_origin.length == _amount.length,
"mismatching input"
);
for (uint256 index = 0; index < _origin.length; index++) {
_migrateFrom(
_origin[index],
_destination[index],
_amount[index],
false
);
}
}
/**
* @dev This is an internal function used by the function migrate that helps to
* swap old trb tokens for new ones based on a custom amount and it allows
* the migrator contact to swap contract locked tokens even if the user has previosly migrated.
* @param _origin is the address of the user to migrate the balance from
* @param _destination is the address that will receive tokens
* @param _amount is the amount to mint to the user
* @param _bypass is a flag used by the migrator to allow it to bypass the "migrated = true" flag
*/
function _migrateFrom(
address _origin,
address _destination,
uint256 _amount,
bool _bypass
) internal {
if (!_bypass) require(!migrated[_origin], "already migrated");
_doMint(_destination, _amount);
migrated[_origin] = true;
}
/**
* @dev This is function used by the function migrate that helps to
* swap old trb tokens for new ones based on the user's old Tellor balance
* @param _destination is the address that will receive tokens
* @param _amount is the amount to mint to the user
*/
function migrateFor(
address _destination,
uint256 _amount,
bool _bypass
) external {
require(msg.sender == addresses[_MIGRATOR], "not allowed");
_migrateFor(_destination, _amount, _bypass);
}
/**
* @dev This is an internal function used by the function migrate that helps to
* swap old trb tokens for new ones based on a custom amount
* @param _destination is the address that will receive tokens
* @param _amount is the amount to mint to the user
*/
function migrateForBatch(
address[] calldata _destination,
uint256[] calldata _amount
) external {
require(msg.sender == addresses[_MIGRATOR], "not allowed");
require(_amount.length == _destination.length, "mismatching input");
for (uint256 index = 0; index < _destination.length; index++) {
_migrateFor(_destination[index], _amount[index], false);
}
}
/**
* @dev This is an internal function used by the function migrate that helps to
* swap old trb tokens for new ones based on a custom amount
* @param _destination is the address that will receive tokens
* @param _amount is the amount to mint to the user
* @param _bypass is true if the migrator contract needs to bypass the migrated = true flag
* for users that have already migrated
*/
function _migrateFor(
address _destination,
uint256 _amount,
bool _bypass
) internal {
if (!_bypass) require(!migrated[_destination], "already migrated");
_doMint(_destination, _amount);
migrated[_destination] = true;
}
/**
* @dev This function allows users to swap old trb tokens for new ones based
* on the user's old Tellor balance
*/
function migrate() external {
_migrate(msg.sender);
}
/**
* @dev This function allows miners to submit their mining solution and data requested
* @param _nonce is the mining solution
* @param _requestIds are the 5 request ids being mined
* @param _values are the 5 values corresponding to the 5 request ids
*/
function submitMiningSolution(
string calldata _nonce,
uint256[5] calldata _requestIds,
uint256[5] calldata _values
) external {
bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender));
require(
uints[_hashMsgSender] == 0 ||
block.timestamp - uints[_hashMsgSender] > 15 minutes,
"Miner can only win rewards once per 15 min"
);
if (uints[_SLOT_PROGRESS] != 4) {
_verifyNonce(_nonce);
}
uints[_hashMsgSender] = block.timestamp;
_submitMiningSolution(_nonce, _requestIds, _values);
}
/**
* @dev This is an internal function used by submitMiningSolution to allow miners to submit
* their mining solution and data requested. It checks the miner is staked, has not
* won in the last 15 min, and checks they are submitting all the correct requestids
* @param _nonce is the mining solution
* @param _requestIds are the 5 request ids being mined
* @param _values are the 5 values corresponding to the 5 request ids
*/
function _submitMiningSolution(
string memory _nonce,
uint256[5] memory _requestIds,
uint256[5] memory _values
) internal {
//Verifying Miner Eligibility
bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender));
require(
stakerDetails[msg.sender].currentStatus == 1,
"Miner status is not staker"
);
require(
_requestIds[0] == currentMiners[0].value,
"Request ID is wrong"
);
require(
_requestIds[1] == currentMiners[1].value,
"Request ID is wrong"
);
require(
_requestIds[2] == currentMiners[2].value,
"Request ID is wrong"
);
require(
_requestIds[3] == currentMiners[3].value,
"Request ID is wrong"
);
require(
_requestIds[4] == currentMiners[4].value,
"Request ID is wrong"
);
uints[_hashMsgSender] = block.timestamp;
bytes32 _currChallenge = bytesVars[_CURRENT_CHALLENGE];
uint256 _slotP = uints[_SLOT_PROGRESS];
//Checking and updating Miner Status
require(
minersByChallenge[_currChallenge][msg.sender] == false,
"Miner already submitted the value"
);
//Update the miner status to true once they submit a value so they don't submit more than once
minersByChallenge[_currChallenge][msg.sender] = true;
//Updating Request
Request storage _tblock = requestDetails[uints[_T_BLOCK]];
//Assigning directly is cheaper than using a for loop
_tblock.valuesByTimestamp[0][_slotP] = _values[0];
_tblock.valuesByTimestamp[1][_slotP] = _values[1];
_tblock.valuesByTimestamp[2][_slotP] = _values[2];
_tblock.valuesByTimestamp[3][_slotP] = _values[3];
_tblock.valuesByTimestamp[4][_slotP] = _values[4];
_tblock.minersByValue[0][_slotP] = msg.sender;
_tblock.minersByValue[1][_slotP] = msg.sender;
_tblock.minersByValue[2][_slotP] = msg.sender;
_tblock.minersByValue[3][_slotP] = msg.sender;
_tblock.minersByValue[4][_slotP] = msg.sender;
if (_slotP + 1 == 4) {
_adjustDifficulty();
}
emit NonceSubmitted(
msg.sender,
_nonce,
_requestIds,
_values,
_currChallenge,
_slotP
);
if (_slotP + 1 == 5) {
//slotProgress has been incremented, but we're using the variable on stack to save gas
_newBlock(_nonce, _requestIds);
uints[_SLOT_PROGRESS] = 0;
} else {
uints[_SLOT_PROGRESS]++;
}
}
/**
* @dev This is an internal function used by submitMiningSolution to allows miners to submit
* their mining solution and data requested. It checks the miner has submitted a
* valid nonce or allows any solution if 15 minutes or more have passed since last
* mine values
* @param _nonce is the mining solution
*/
function _verifyNonce(string memory _nonce) internal view {
require(
uint256(
sha256(
abi.encodePacked(
ripemd160(
abi.encodePacked(
keccak256(
abi.encodePacked(
bytesVars[_CURRENT_CHALLENGE],
msg.sender,
_nonce
)
)
)
)
)
)
) %
uints[_DIFFICULTY] ==
0 ||
block.timestamp - uints[_TIME_OF_LAST_NEW_VALUE] >= 15 minutes,
"Incorrect nonce for current challenge"
);
}
/**
* @dev This is an internal function used by submitMiningSolution and adjusts the difficulty
* based on the difference between the target time and how long it took to solve
* the previous challenge otherwise it sets it to 1
*/
function _adjustDifficulty() internal {
// If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge
// difficulty up or down by the difference between the target time and how long it took to solve the previous challenge
// otherwise it sets it to 1
uint256 timeDiff = block.timestamp - uints[_TIME_OF_LAST_NEW_VALUE];
int256 _change = int256(SafeMath.min(1200, timeDiff));
int256 _diff = int256(uints[_DIFFICULTY]);
_change = (_diff * (int256(uints[_TIME_TARGET]) - _change)) / 4000;
if (_change == 0) {
_change = 1;
}
uints[_DIFFICULTY] = uint256(SafeMath.max(_diff + _change, 1));
}
/**
* @dev This is an internal function used by submitMiningSolution to
* calculate and pay rewards to miners
* @param miners are the 5 miners to reward
* @param _previousTime is the previous mine time based on the 4th entry
*/
function _payReward(address[5] memory miners, uint256 _previousTime)
internal
{
//_timeDiff is how many seconds passed since last block
uint256 _timeDiff = block.timestamp - _previousTime;
uint256 reward = (_timeDiff * uints[_CURRENT_REWARD]) / 300;
uint256 _tip = uints[_CURRENT_TOTAL_TIPS] / 10;
uint256 _devShare = reward / 2;
_doMint(miners[0], reward + _tip);
_doMint(miners[1], reward + _tip);
_doMint(miners[2], reward + _tip);
_doMint(miners[3], reward + _tip);
_doMint(miners[4], reward + _tip);
_doMint(addresses[_OWNER], _devShare);
uints[_CURRENT_TOTAL_TIPS] = 0;
}
/**
* @dev This is an internal function called by submitMiningSolution and adjusts the difficulty,
* sorts and stores the first 5 values received, pays the miners, the dev share and
* assigns a new challenge
* @param _nonce or solution for the PoW for the requestId
* @param _requestIds for the current request being mined
*/
function _newBlock(string memory _nonce, uint256[5] memory _requestIds)
internal
{
Request storage _tblock = requestDetails[uints[_T_BLOCK]];
bytes32 _currChallenge = bytesVars[_CURRENT_CHALLENGE];
uint256 _previousTime = uints[_TIME_OF_LAST_NEW_VALUE];
uint256 _timeOfLastNewValueVar = block.timestamp;
uints[_TIME_OF_LAST_NEW_VALUE] = _timeOfLastNewValueVar;
//this loop sorts the values and stores the median as the official value
uint256[5] memory a;
uint256[5] memory b;
for (uint256 k = 0; k < 5; k++) {
for (uint256 i = 1; i < 5; i++) {
uint256 temp = _tblock.valuesByTimestamp[k][i];
address temp2 = _tblock.minersByValue[k][i];
uint256 j = i;
while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) {
_tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[
k
][j - 1];
_tblock.minersByValue[k][j] = _tblock.minersByValue[k][
j - 1
];
j--;
}
if (j < i) {
_tblock.valuesByTimestamp[k][j] = temp;
_tblock.minersByValue[k][j] = temp2;
}
}
Request storage _request = requestDetails[_requestIds[k]];
//Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number
a = _tblock.valuesByTimestamp[k];
_request.finalValues[_timeOfLastNewValueVar] = a[2];
b[k] = a[2];
_request.minersByValue[_timeOfLastNewValueVar] = _tblock
.minersByValue[k];
_request.valuesByTimestamp[_timeOfLastNewValueVar] = _tblock
.valuesByTimestamp[k];
delete _tblock.minersByValue[k];
delete _tblock.valuesByTimestamp[k];
_request.requestTimestamps.push(_timeOfLastNewValueVar);
_request.minedBlockNum[_timeOfLastNewValueVar] = block.number;
_request.apiUintVars[_TOTAL_TIP] = 0;
}
emit NewValue(
_requestIds,
_timeOfLastNewValueVar,
b,
uints[_CURRENT_TOTAL_TIPS],
_currChallenge
);
//add timeOfLastValue to the newValueTimestamps array
newValueTimestamps.push(_timeOfLastNewValueVar);
address[5] memory miners =
requestDetails[_requestIds[0]].minersByValue[
_timeOfLastNewValueVar
];
//pay Miners Rewards
_payReward(miners, _previousTime);
uints[_T_BLOCK]++;
uint256[5] memory _topId = _getTopRequestIDs();
for (uint256 i = 0; i < 5; i++) {
currentMiners[i].value = _topId[i];
requestQ[
requestDetails[_topId[i]].apiUintVars[_REQUEST_Q_POSITION]
] = 0;
uints[_CURRENT_TOTAL_TIPS] += requestDetails[_topId[i]].apiUintVars[
_TOTAL_TIP
];
}
// Issue the next challenge
_currChallenge = keccak256(
abi.encode(_nonce, _currChallenge, blockhash(block.number - 1))
);
bytesVars[_CURRENT_CHALLENGE] = _currChallenge; // Save hash for next proof
emit NewChallenge(
_currChallenge,
_topId,
uints[_DIFFICULTY],
uints[_CURRENT_TOTAL_TIPS]
);
}
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(uint256 _requestId, uint256 _tip) external {
require(_requestId != 0, "RequestId is 0");
require(_tip != 0, "Tip should be greater than 0");
uint256 _count = uints[_REQUEST_COUNT] + 1;
if (_requestId == _count) {
uints[_REQUEST_COUNT] = _count;
} else {
require(_requestId < _count, "RequestId is not less than count");
}
_doBurn(msg.sender, _tip);
//Update the information for the request that should be mined next based on the tip submitted
updateOnDeck(_requestId, _tip);
emit TipAdded(
msg.sender,
_requestId,
_tip,
requestDetails[_requestId].apiUintVars[_TOTAL_TIP]
);
}
/**
* @dev This function updates the requestQ when addTip are ran
* @param _requestId being requested
* @param _tip is the tip to add
*/
function updateOnDeck(uint256 _requestId, uint256 _tip) internal {
Request storage _request = requestDetails[_requestId];
_request.apiUintVars[_TOTAL_TIP] = _request.apiUintVars[_TOTAL_TIP].add(
_tip
);
if (
currentMiners[0].value == _requestId ||
currentMiners[1].value == _requestId ||
currentMiners[2].value == _requestId ||
currentMiners[3].value == _requestId ||
currentMiners[4].value == _requestId
) {
uints[_CURRENT_TOTAL_TIPS] += _tip;
} else {
// if the request is not part of the requestQ[51] array
// then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array
if (_request.apiUintVars[_REQUEST_Q_POSITION] == 0) {
uint256 _min;
uint256 _index;
(_min, _index) = _getMin(requestQ);
//we have to zero out the oldOne
//if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero
//then add it to the requestQ array and map its index information to the requestId and the apiUintVars
if (_request.apiUintVars[_TOTAL_TIP] > _min || _min == 0) {
requestQ[_index] = _request.apiUintVars[_TOTAL_TIP];
requestDetails[requestIdByRequestQIndex[_index]]
.apiUintVars[_REQUEST_Q_POSITION] = 0;
requestIdByRequestQIndex[_index] = _requestId;
_request.apiUintVars[_REQUEST_Q_POSITION] = _index;
}
// else if the requestId is part of the requestQ[51] then update the tip for it
} else {
requestQ[_request.apiUintVars[_REQUEST_Q_POSITION]] += _tip;
}
}
}
/**
* @dev This is an internal function called by updateOnDeck that gets the min value
* @param data is an array [51] to determine the min from
* @return min the min value and it's index in the data array
*/
function _getMin(uint256[51] memory data)
internal
pure
returns (uint256 min, uint256 minIndex)
{
minIndex = data.length - 1;
min = data[minIndex];
for (uint256 i = data.length - 2; i > 0; i--) {
if (data[i] < min) {
min = data[i];
minIndex = i;
}
}
}
/**
* @dev This is an internal function called by updateOnDeck that gets the top 5 values
* @param data is an array [51] to determine the top 5 values from
* @return max the top 5 values and their index values in the data array
*/
function _getMax5(uint256[51] memory data)
internal
pure
returns (uint256[5] memory max, uint256[5] memory maxIndex)
{
uint256 min5 = data[1];
uint256 minI = 0;
for (uint256 j = 0; j < 5; j++) {
max[j] = data[j + 1]; //max[0]=data[1]
maxIndex[j] = j + 1; //maxIndex[0]= 1
if (max[j] < min5) {
min5 = max[j];
minI = j;
}
}
for (uint256 i = 6; i < data.length; i++) {
if (data[i] > min5) {
max[minI] = data[i];
maxIndex[minI] = i;
min5 = data[i];
for (uint256 j = 0; j < 5; j++) {
if (max[j] < min5) {
min5 = max[j];
minI = j;
}
}
}
}
}
/**
* @dev Getter function for the top 5 requests with highest payouts.
* This function is used within the newBlock function
* @return _requestIds the top 5 requests ids based on tips or the last 5 requests ids mined
*/
function _getTopRequestIDs()
internal
view
returns (uint256[5] memory _requestIds)
{
uint256[5] memory _max;
uint256[5] memory _index;
(_max, _index) = _getMax5(requestQ);
for (uint256 i = 0; i < 5; i++) {
if (_max[i] != 0) {
_requestIds[i] = requestIdByRequestQIndex[_index[i]];
} else {
_requestIds[i] = currentMiners[4 - i].value;
}
}
}
/**
* @dev This is an internal function called within the fallback function to help delegate calls.
* This functions helps delegate calls to the TellorGetters
* contract.
*/
function _delegate(address implementation)
internal
virtual
returns (bool succ, bytes memory ret)
{
(succ, ret) = implementation.delegatecall(msg.data);
}
/**
* @dev The tellor logic does not fit in one contract so it has been split into two:
* Tellor and TellorGetters This functions helps delegate calls to the TellorGetters
* contract.
*/
fallback() external payable {
address addr = addresses[_EXTENSION];
(bool result, ) = _delegate(addr);
assembly {
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "./TellorTransfer.sol";
import "./TellorGetters.sol";
import "./Extension.sol";
import "./Utilities.sol";
/**
* title Tellor Stake
* @dev Contains the methods related to initiating disputes and
* voting on them.
* Because of space limitations some functions are currently on the Extensions contract
*/
contract TellorStake is TellorTransfer {
using SafeMath for uint256;
using SafeMath for int256;
//emitted when a new dispute is initialized
event NewDispute(
uint256 indexed _disputeId,
uint256 indexed _requestId,
uint256 _timestamp,
address _miner
);
//emitted when a new vote happens
event Voted(
uint256 indexed _disputeID,
bool _position,
address indexed _voter,
uint256 indexed _voteWeight
);
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false/bad value on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(
uint256 _requestId,
uint256 _timestamp,
uint256 _minerIndex
) public {
Request storage _request = requestDetails[_requestId];
require(_request.minedBlockNum[_timestamp] != 0, "Mined block is 0");
require(_minerIndex < 5, "Miner index is wrong");
//_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex
//provided by the party initiating the dispute
address _miner = _request.minersByValue[_timestamp][_minerIndex];
bytes32 _hash =
keccak256(abi.encodePacked(_miner, _requestId, _timestamp));
//Increase the dispute count by 1
uint256 disputeId = uints[_DISPUTE_COUNT] + 1;
uints[_DISPUTE_COUNT] = disputeId;
//Ensures that a dispute is not already open for the that miner, requestId and timestamp
uint256 hashId = disputeIdByDisputeHash[_hash];
if (hashId != 0) {
disputesById[disputeId].disputeUintVars[_ORIGINAL_ID] = hashId;
} else {
disputeIdByDisputeHash[_hash] = disputeId;
hashId = disputeId;
}
uint256 origID = hashId;
uint256 dispRounds =
disputesById[origID].disputeUintVars[_DISPUTE_ROUNDS] + 1;
disputesById[origID].disputeUintVars[_DISPUTE_ROUNDS] = dispRounds;
disputesById[origID].disputeUintVars[
keccak256(abi.encode(dispRounds))
] = disputeId;
if (disputeId != origID) {
uint256 lastID =
disputesById[origID].disputeUintVars[
keccak256(abi.encode(dispRounds - 1))
];
require(
disputesById[lastID].disputeUintVars[_MIN_EXECUTION_DATE] <=
block.timestamp,
"Dispute is already open"
);
if (disputesById[lastID].executed) {
require(
block.timestamp -
disputesById[lastID].disputeUintVars[_TALLY_DATE] <=
1 days,
"Time for voting haven't elapsed"
);
}
}
uint256 _fee;
if (_minerIndex == 2) {
requestDetails[_requestId].apiUintVars[_DISPUTE_COUNT] =
requestDetails[_requestId].apiUintVars[_DISPUTE_COUNT] +
1;
//update dispute fee for this case
_fee =
uints[_STAKE_AMOUNT] *
requestDetails[_requestId].apiUintVars[_DISPUTE_COUNT];
} else {
_fee = uints[_DISPUTE_FEE] * dispRounds;
}
//maps the dispute to the Dispute struct
disputesById[disputeId].hash = _hash;
disputesById[disputeId].isPropFork = false;
disputesById[disputeId].reportedMiner = _miner;
disputesById[disputeId].reportingParty = msg.sender;
disputesById[disputeId].proposedForkAddress = address(0);
disputesById[disputeId].executed = false;
disputesById[disputeId].disputeVotePassed = false;
disputesById[disputeId].tally = 0;
//Saves all the dispute variables for the disputeId
disputesById[disputeId].disputeUintVars[_REQUEST_ID] = _requestId;
disputesById[disputeId].disputeUintVars[_TIMESTAMP] = _timestamp;
disputesById[disputeId].disputeUintVars[_VALUE] = _request
.valuesByTimestamp[_timestamp][_minerIndex];
disputesById[disputeId].disputeUintVars[_MIN_EXECUTION_DATE] =
block.timestamp +
2 days *
dispRounds;
disputesById[disputeId].disputeUintVars[_BLOCK_NUMBER] = block.number;
disputesById[disputeId].disputeUintVars[_MINER_SLOT] = _minerIndex;
disputesById[disputeId].disputeUintVars[_FEE] = _fee;
_doTransfer(msg.sender, address(this), _fee);
//Values are sorted as they come in and the official value is the median of the first five
//So the "official value" miner is always minerIndex==2. If the official value is being
//disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute
if (_minerIndex == 2) {
_request.inDispute[_timestamp] = true;
_request.finalValues[_timestamp] = 0;
}
stakerDetails[_miner].currentStatus = 3;
emit NewDispute(disputeId, _requestId, _timestamp, _miner);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(uint256 _disputeId, bool _supportsDispute) public {
Dispute storage disp = disputesById[_disputeId];
//Get the voteWeight or the balance of the user at the time/blockNumber the dispute began
uint256 voteWeight =
balanceOfAt(msg.sender, disp.disputeUintVars[_BLOCK_NUMBER]);
//Require that the msg.sender has not voted
require(disp.voted[msg.sender] != true, "Sender has already voted");
//Require that the user had a balance >0 at time/blockNumber the dispute began
require(voteWeight != 0, "User balance is 0");
//ensures miners that are under dispute cannot vote
require(
stakerDetails[msg.sender].currentStatus != 3,
"Miner is under dispute"
);
//Update user voting status to true
disp.voted[msg.sender] = true;
//Update the number of votes for the dispute
disp.disputeUintVars[_NUM_OF_VOTES] += 1;
//If the user supports the dispute increase the tally for the dispute by the voteWeight
//otherwise decrease it
if (_supportsDispute) {
disp.tally = disp.tally.add(int256(voteWeight));
} else {
disp.tally = disp.tally.sub(int256(voteWeight));
}
//Let the network kblock.timestamp the user has voted on the dispute and their casted vote
emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight);
}
/**
* @dev Allows disputer to unlock the dispute fee
* @param _disputeId to unlock fee from
*/
function unlockDisputeFee(uint256 _disputeId) public {
uint256 origID = disputeIdByDisputeHash[disputesById[_disputeId].hash];
uint256 lastID =
disputesById[origID].disputeUintVars[
keccak256(
abi.encode(
disputesById[origID].disputeUintVars[_DISPUTE_ROUNDS]
)
)
];
if (lastID == 0) {
lastID = origID;
}
Dispute storage disp = disputesById[origID];
Dispute storage last = disputesById[lastID];
//disputeRounds is increased by 1 so that the _id is not a negative number when it is the first time a dispute is initiated
uint256 dispRounds = disp.disputeUintVars[_DISPUTE_ROUNDS];
if (dispRounds == 0) {
dispRounds = 1;
}
uint256 _id;
require(disp.disputeUintVars[_PAID] == 0, "already paid out");
require(
block.timestamp - last.disputeUintVars[_TALLY_DATE] > 1 days,
"Time for voting haven't elapsed"
);
StakeInfo storage stakes = stakerDetails[disp.reportedMiner];
disp.disputeUintVars[_PAID] = 1;
if (last.disputeVotePassed == true) {
//Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount
stakes.startDate = block.timestamp - (block.timestamp % 86400);
//Reduce the staker count
uints[_STAKE_COUNT] -= 1;
//Update the minimum dispute fee that is based on the number of
// Not ideal, but allows to keep updateMinDosputeFee in the extension contract
addresses[_EXTENSION].delegatecall(
abi.encodeWithSignature("updateMinDisputeFee")
);
//Decreases the stakerCount since the miner's stake is being slashed
if (stakes.currentStatus == 4) {
stakes.currentStatus = 5;
_doTransfer(
disp.reportedMiner,
disp.reportingParty,
uints[_STAKE_AMOUNT]
);
stakes.currentStatus = 0;
}
for (uint256 i = 0; i < dispRounds; i++) {
_id = disp.disputeUintVars[
keccak256(abi.encode(dispRounds - i))
];
if (_id == 0) {
_id = origID;
}
Dispute storage disp2 = disputesById[_id];
//transfer fee adjusted based on number of miners if the minerIndex is not 2(official value)
_doTransfer(
address(this),
disp2.reportingParty,
disp2.disputeUintVars[_FEE]
);
}
} else {
stakes.currentStatus = 1;
TellorStorage.Request storage _request =
requestDetails[disp.disputeUintVars[_REQUEST_ID]];
if (disp.disputeUintVars[_MINER_SLOT] == 2) {
//note we still don't put timestamp back into array (is this an issue? (shouldn't be))
_request.finalValues[disp.disputeUintVars[_TIMESTAMP]] = disp
.disputeUintVars[_VALUE];
}
if (_request.inDispute[disp.disputeUintVars[_TIMESTAMP]] == true) {
_request.inDispute[disp.disputeUintVars[_TIMESTAMP]] = false;
}
for (uint256 i = 0; i < dispRounds; i++) {
_id = disp.disputeUintVars[
keccak256(abi.encode(dispRounds - i))
];
if (_id != 0) {
last = disputesById[_id]; //handling if happens during an upgrade
}
_doTransfer(
address(this),
last.reportedMiner,
disputesById[_id].disputeUintVars[_FEE]
);
}
}
if (disp.disputeUintVars[_MINER_SLOT] == 2) {
requestDetails[disp.disputeUintVars[_REQUEST_ID]].apiUintVars[
_DISPUTE_COUNT
]--;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "./SafeMath.sol";
import "./TellorStorage.sol";
import "./TellorVariables.sol";
import "./Utilities.sol";
/**
* @title Tellor Getters
* @dev Oracle contract with all tellor getter functions
*/
contract TellorGetters is TellorStorage, TellorVariables, Utilities {
using SafeMath for uint256;
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(bytes32 _challenge, address _miner)
public
view
returns (bool)
{
return minersByChallenge[_challenge][_miner];
}
/**
* @dev Checks if an address voted in a given dispute
* @param _disputeId to look up
* @param _address to look up
* @return bool of whether or not party voted
*/
function didVote(uint256 _disputeId, address _address)
external
view
returns (bool)
{
return disputesById[_disputeId].voted[_address];
}
/**
* @dev allows Tellor to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("tellorContract")]
* @return address of the requested variable
*/
function getAddressVars(bytes32 _data) external view returns (address) {
return addresses[_data];
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* bool executed where true if it has been voted on
* bool disputeVotePassed
* bool isPropFork true if the dispute is a proposed fork
* address of reportedMiner
* address of reportingParty
* address of proposedForkAddress
* uint of requestId
* uint of timestamp
* uint of value
* uint of minExecutionDate
* uint of numberOfVotes
* uint of blocknumber
* uint of minerSlot
* uint of quorum
* uint of fee
* int count of the current tally
*/
function getAllDisputeVars(uint256 _disputeId)
public
view
returns (
bytes32,
bool,
bool,
bool,
address,
address,
address,
uint256[9] memory,
int256
)
{
Dispute storage disp = disputesById[_disputeId];
return (
disp.hash,
disp.executed,
disp.disputeVotePassed,
disp.isPropFork,
disp.reportedMiner,
disp.reportingParty,
disp.proposedForkAddress,
[
disp.disputeUintVars[_REQUEST_ID],
disp.disputeUintVars[_TIMESTAMP],
disp.disputeUintVars[_VALUE],
disp.disputeUintVars[_MIN_EXECUTION_DATE],
disp.disputeUintVars[_NUM_OF_VOTES],
disp.disputeUintVars[_BLOCK_NUMBER],
disp.disputeUintVars[_MINER_SLOT],
disp.disputeUintVars[keccak256("quorum")],
disp.disputeUintVars[_FEE]
],
disp.tally
);
}
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId,_timestamp));
* @return uint disputeId
*/
function getDisputeIdByDisputeHash(bytes32 _hash)
external
view
returns (uint256)
{
return disputeIdByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(uint256 _disputeId, bytes32 _data)
external
view
returns (uint256)
{
return disputesById[_disputeId].disputeUintVars[_data];
}
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submitted
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue() external view returns (uint256, bool) {
return (
retrieveData(
requestIdByTimestamp[uints[_TIME_OF_LAST_NEW_VALUE]],
uints[_TIME_OF_LAST_NEW_VALUE]
),
true
);
}
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submitted and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(uint256 _requestId)
external
view
returns (uint256, bool)
{
Request storage _request = requestDetails[_requestId];
if (_request.requestTimestamps.length != 0) {
return (
retrieveData(
_requestId,
_request.requestTimestamps[
_request.requestTimestamps.length - 1
]
),
true
);
} else {
return (0, false);
}
}
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256)
{
return requestDetails[_requestId].minedBlockNum[_timestamp];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(
uint256 _requestId,
uint256 _timestamp
) external view returns (address[5] memory) {
return requestDetails[_requestId].minersByValue[_timestamp];
}
/**
* @dev Counts the number of values that have been submitted for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint256 _requestId)
external
view
returns (uint256)
{
return requestDetails[_requestId].requestTimestamps.length;
}
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of requestId
*/
function getRequestIdByRequestQIndex(uint256 _index)
external
view
returns (uint256)
{
require(_index <= 50, "RequestQ index is above 50");
return requestIdByRequestQIndex[_index];
}
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of requestId
*/
function getRequestIdByTimestamp(uint256 _timestamp)
external
view
returns (uint256)
{
return requestIdByTimestamp[_timestamp];
}
/**
* @dev Getter function for the requestQ array
* @return the requestQ array
*/
function getRequestQ() public view returns (uint256[51] memory) {
return requestQ;
}
/**
* @dev Allows access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(uint256 _requestId, bytes32 _data)
external
view
returns (uint256)
{
return requestDetails[_requestId].apiUintVars[_data];
}
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(uint256 _requestId)
external
view
returns (uint256, uint256)
{
Request storage _request = requestDetails[_requestId];
return (
_request.apiUintVars[_REQUEST_Q_POSITION],
_request.apiUintVars[_TOTAL_TIP]
);
}
/**
* @dev This function allows users to retrieve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(address _staker)
external
view
returns (uint256, uint256)
{
return (
stakerDetails[_staker].currentStatus,
stakerDetails[_staker].startDate
);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return address[5] array of 5 addresses of miners that mined the requestId
*/
function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256[5] memory)
{
return requestDetails[_requestId].valuesByTimestamp[_timestamp];
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index)
external
view
returns (uint256)
{
return requestDetails[_requestID].requestTimestamps[_index];
}
/**
* @dev Getter for the variables saved under the TellorStorageStruct uints variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name")
* where variable_name is the variables/strings used to save the data in the mapping.
* The variables names in the TellorVariables contract
* @return uint of specified variable
*/
function getUintVar(bytes32 _data) public view returns (uint256) {
return uints[_data];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(uint256 _requestId, uint256 _timestamp)
external
view
returns (bool)
{
return requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retrieve value from oracle based on timestamp
* @param _requestId being requested
* @param _timestamp to retrieve data/value from
* @return value for timestamp submitted
*/
function retrieveData(uint256 _requestId, uint256 _timestamp)
public
view
returns (uint256)
{
return requestDetails[_requestId].finalValues[_timestamp];
}
/**
* @dev Getter for the total_supply of oracle tokens
* @return uint total supply
*/
function totalSupply() external view returns (uint256) {
return uints[_TOTAL_SUPPLY];
}
/**
* @dev Allows users to access the token's name
*/
function name() external pure returns (string memory) {
return "Tellor Tributes";
}
/**
* @dev Allows users to access the token's symbol
*/
function symbol() external pure returns (string memory) {
return "TRB";
}
/**
* @dev Allows users to access the number of decimals
*/
function decimals() external pure returns (uint8) {
return 18;
}
/**
* @dev Getter function for the requestId being mined
* returns the currentChallenge, array of requestIDs, difficulty, and the current Tip of the 5 IDs
*/
function getNewCurrentVariables()
external
view
returns (
bytes32 _challenge,
uint256[5] memory _requestIds,
uint256 _diff,
uint256 _tip
)
{
for (uint256 i = 0; i < 5; i++) {
_requestIds[i] = currentMiners[i].value;
}
return (
bytesVars[_CURRENT_CHALLENGE],
_requestIds,
uints[_DIFFICULTY],
uints[_CURRENT_TOTAL_TIPS]
);
}
/**
* @dev Getter function for next requestIds on queue/request with highest payouts at time the function is called
*/
function getNewVariablesOnDeck()
external
view
returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck)
{
idsOnDeck = getTopRequestIDs();
for (uint256 i = 0; i < 5; i++) {
tipsOnDeck[i] = requestDetails[idsOnDeck[i]].apiUintVars[
_TOTAL_TIP
];
}
}
/**
* @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function
*/
function getTopRequestIDs()
public
view
returns (uint256[5] memory _requestIds)
{
uint256[5] memory _max;
uint256[5] memory _index;
(_max, _index) = getMax5(requestQ);
for (uint256 i = 0; i < 5; i++) {
if (_max[i] != 0) {
_requestIds[i] = requestIdByRequestQIndex[_index[i]];
} else {
_requestIds[i] = currentMiners[4 - i].value;
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
//Functions for retrieving min and Max in 51 length array (requestQ)
//Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol
contract Utilities {
/**
* @dev This is an internal function called by updateOnDeck that gets the top 5 values
* @param data is an array [51] to determine the top 5 values from
* @return max the top 5 values and their index values in the data array
*/
function getMax5(uint256[51] memory data)
public
view
returns (uint256[5] memory max, uint256[5] memory maxIndex)
{
uint256 min5 = data[1];
uint256 minI = 0;
for (uint256 j = 0; j < 5; j++) {
max[j] = data[j + 1]; //max[0]=data[1]
maxIndex[j] = j + 1; //maxIndex[0]= 1
if (max[j] < min5) {
min5 = max[j];
minI = j;
}
}
for (uint256 i = 6; i < data.length; i++) {
if (data[i] > min5) {
max[minI] = data[i];
maxIndex[minI] = i;
min5 = data[i];
for (uint256 j = 0; j < 5; j++) {
if (max[j] < min5) {
min5 = max[j];
minI = j;
}
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
interface ITellor {
event NewTellorAddress(address _newTellor);
event NewDispute(
uint256 indexed _disputeId,
uint256 indexed _requestId,
uint256 _timestamp,
address _miner
);
event Voted(
uint256 indexed _disputeID,
bool _position,
address indexed _voter,
uint256 indexed _voteWeight
);
event DisputeVoteTallied(
uint256 indexed _disputeID,
int256 _result,
address indexed _reportedMiner,
address _reportingParty,
bool _active
);
event TipAdded(
address indexed _sender,
uint256 indexed _requestId,
uint256 _tip,
uint256 _totalTips
);
event NewChallenge(
bytes32 indexed _currentChallenge,
uint256[5] _currentRequestId,
uint256 _difficulty,
uint256 _totalTips
);
event NewValue(
uint256[5] _requestId,
uint256 _time,
uint256[5] _value,
uint256 _totalTips,
bytes32 indexed _currentChallenge
);
event NonceSubmitted(
address indexed _miner,
string _nonce,
uint256[5] _requestId,
uint256[5] _value,
bytes32 indexed _currentChallenge
);
event OwnershipTransferred(
address indexed _previousOwner,
address indexed _newOwner
);
event OwnershipProposed(
address indexed _previousOwner,
address indexed _newOwner
);
event NewStake(address indexed _sender); //Emits upon new staker
event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked
event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
); //ERC20 Approval event
event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event
function changeDeity(address _newDeity) external;
function changeTellorContract(address _tellorContract) external;
function allowance(address _user, address _spender)
external
view
returns (uint256);
function allowedToTrade(address _user, uint256 _amount)
external
view
returns (bool);
function balanceOf(address _user) external view returns (uint256);
function balanceOfAt(address _user, uint256 _blockNumber)
external
view
returns (uint256);
function didMine(bytes32 _challenge, address _miner)
external
view
returns (bool);
function didVote(uint256 _disputeId, address _address)
external
view
returns (bool);
function getAddressVars(bytes32 _data) external view returns (address);
function getAllDisputeVars(uint256 _disputeId)
external
view
returns (
bytes32,
bool,
bool,
bool,
address,
address,
address,
uint256[9] memory,
int256
);
function getCurrentVariables()
external
view
returns (
bytes32,
uint256,
uint256,
string memory,
uint256,
uint256
);
function getDisputeIdByDisputeHash(bytes32 _hash)
external
view
returns (uint256);
function getDisputeUintVars(uint256 _disputeId, bytes32 _data)
external
view
returns (uint256);
function getLastNewValue() external view returns (uint256, bool);
function getLastNewValueById(uint256 _requestId)
external
view
returns (uint256, bool);
function getMinedBlockNum(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256);
function getMinersByRequestIdAndTimestamp(
uint256 _requestId,
uint256 _timestamp
) external view returns (address[5] memory);
function getNewValueCountbyRequestId(uint256 _requestId)
external
view
returns (uint256);
function getRequestIdByRequestQIndex(uint256 _index)
external
view
returns (uint256);
function getRequestIdByTimestamp(uint256 _timestamp)
external
view
returns (uint256);
function getRequestIdByQueryHash(bytes32 _request)
external
view
returns (uint256);
function getRequestQ() external view returns (uint256[51] memory);
function getRequestUintVars(uint256 _requestId, bytes32 _data)
external
view
returns (uint256);
function getRequestVars(uint256 _requestId)
external
view
returns (uint256, uint256);
function getStakerInfo(address _staker)
external
view
returns (uint256, uint256);
function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256[5] memory);
function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index)
external
view
returns (uint256);
function getUintVar(bytes32 _data) external view returns (uint256);
function getVariablesOnDeck()
external
view
returns (
uint256,
uint256,
string memory
);
function isInDispute(uint256 _requestId, uint256 _timestamp)
external
view
returns (bool);
function retrieveData(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256);
function totalSupply() external view returns (uint256);
function beginDispute(
uint256 _requestId,
uint256 _timestamp,
uint256 _minerIndex
) external;
function vote(uint256 _disputeId, bool _supportsDispute) external;
function tallyVotes(uint256 _disputeId) external;
function proposeFork(address _propNewTellorAddress) external;
function addTip(uint256 _requestId, uint256 _tip) external;
function submitMiningSolution(
string calldata _nonce,
uint256[5] calldata _requestId,
uint256[5] calldata _value
) external;
function proposeOwnership(address payable _pendingOwner) external;
function claimOwnership() external;
function depositStake() external;
function requestStakingWithdraw() external;
function withdrawStake() external;
function approve(address _spender, uint256 _amount) external returns (bool);
function transfer(address _to, uint256 _amount) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _amount
) external returns (bool);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function getNewCurrentVariables()
external
view
returns (
bytes32 _challenge,
uint256[5] memory _requestIds,
uint256 _difficutly,
uint256 _tip
);
function getTopRequestIDs()
external
view
returns (uint256[5] memory _requestIds);
function getNewVariablesOnDeck()
external
view
returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck);
function updateTellor(uint256 _disputeId) external;
function unlockDisputeFee(uint256 _disputeId) external;
//Test Functions
function theLazyCoon(address _address, uint256 _amount) external;
function testSubmitMiningSolution(
string calldata _nonce,
uint256[5] calldata _requestId,
uint256[5] calldata _value
) external;
function manuallySetDifficulty(uint256 _diff) external;
function migrate() external;
function getMax(uint256[51] memory data)
external
view
returns (uint256 max, uint256 maxIndex);
function getMin(uint256[51] memory data)
external
view
returns (uint256 min, uint256 minIndex);
function getMax5(uint256[51] memory data)
external
view
returns (uint256[5] memory max, uint256[5] memory maxIndex);
function changeExtension(address _ext) external;
function changeMigrator(address _migrator) external;
function getAddressVarByString(string calldata _data)
external
view
returns (address);
function migrateFrom(
address _origin,
address _destination,
uint256 _amount,
bool _bypass
) external;
function migrateFor(
address _destination,
uint256 _amount,
bool _bypass
) external;
function migrateForBatch(
address[] calldata _destination,
uint256[] calldata _amount
) external;
function migrateFromBatch(
address[] calldata _origin,
address[] calldata _destination,
uint256[] calldata _amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
//Slightly modified SafeMath library - includes a min and max function, removes useless div function
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a + b;
assert(c >= a);
} else {
c = a + b;
assert(c <= a);
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function max(int256 a, int256 b) internal pure returns (uint256) {
return a > b ? uint256(a) : uint256(b);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a - b;
assert(c <= a);
} else {
c = a - b;
assert(c >= a);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "./SafeMath.sol";
import "./TellorStorage.sol";
import "./TellorVariables.sol";
/**
* @title Tellor Transfer
* @dev Contains the methods related to transfers and ERC20, its storage and hashes of tellor variable
* that are used to save gas on transactions.
*/
contract TellorTransfer is TellorStorage, TellorVariables {
using SafeMath for uint256;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/*Functions*/
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
*/
function transfer(address _to, uint256 _amount)
public
returns (bool success)
{
_doTransfer(msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _amount
) public returns (bool success) {
require(
_allowances[_from][msg.sender] >= _amount,
"Allowance is wrong"
);
_allowances[_from][msg.sender] -= _amount;
_doTransfer(_from, _to, _amount);
return true;
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender approved successfully
*/
function approve(address _spender, uint256 _amount) public returns (bool) {
require(
msg.sender != address(0),
"ERC20: approve from the zero address"
);
require(_spender != address(0), "ERC20: approve to the zero address");
_allowances[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Getter function for remaining spender balance
* @param _user address of party with the balance
* @param _spender address of spender of parties said balance
* @return Returns the remaining allowance of tokens granted to the _spender from the _user
*/
function allowance(address _user, address _spender)
public
view
returns (uint256)
{
return _allowances[_user][_spender];
}
/**
* @dev Completes transfers by updating the balances on the current block number
* and ensuring the amount does not contain tokens staked for mining
* @param _from address to transfer from
* @param _to address to transfer to
* @param _amount to transfer
*/
function _doTransfer(
address _from,
address _to,
uint256 _amount
) internal {
require(_amount != 0, "Tried to send non-positive amount");
require(_to != address(0), "Receiver is 0 address");
require(
allowedToTrade(_from, _amount),
"Should have sufficient balance to trade"
);
uint256 previousBalance = balanceOf(_from);
updateBalanceAtNow(_from, previousBalance - _amount);
previousBalance = balanceOf(_to);
require(
previousBalance + _amount >= previousBalance,
"Overflow happened"
); // Check for overflow
updateBalanceAtNow(_to, previousBalance + _amount);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Helps swap the old Tellor contract Tokens to the new one
* @param _to is the adress to send minted amount to
* @param _amount is the amount of TRB to send
*/
function _doMint(address _to, uint256 _amount) internal {
require(_amount != 0, "Tried to mint non-positive amount");
require(_to != address(0), "Receiver is 0 address");
uint256 previousBalance = balanceOf(_to);
require(
previousBalance + _amount >= previousBalance,
"Overflow happened"
); // Check for overflow
uint256 previousSupply = uints[_TOTAL_SUPPLY];
require(
previousSupply + _amount >= previousSupply,
"Overflow happened"
);
uints[_TOTAL_SUPPLY] += _amount;
updateBalanceAtNow(_to, previousBalance + _amount);
emit Transfer(address(0), _to, _amount);
}
/**
* @dev Helps burn TRB Tokens
* @param _from is the adress to burn or remove TRB amount
* @param _amount is the amount of TRB to burn
*/
function _doBurn(address _from, uint256 _amount) internal {
if (_amount == 0) return;
uint256 previousBalance = balanceOf(_from);
require(
previousBalance - _amount <= previousBalance,
"Overflow happened"
); // Check for overflow
uint256 previousSupply = uints[_TOTAL_SUPPLY];
require(
previousSupply - _amount <= previousSupply,
"Overflow happened"
);
updateBalanceAtNow(_from, previousBalance - _amount);
uints[_TOTAL_SUPPLY] -= _amount;
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(address _user) public view returns (uint256) {
return balanceOfAt(_user, block.number);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber specified
*/
function balanceOfAt(address _user, uint256 _blockNumber)
public
view
returns (uint256)
{
TellorStorage.Checkpoint[] storage checkpoints = balances[_user];
if (
checkpoints.length == 0 || checkpoints[0].fromBlock > _blockNumber
) {
return 0;
} else {
if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length - 2;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock == _blockNumber) {
return checkpoints[mid].value;
} else if (checkpoints[mid].fromBlock < _blockNumber) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
}
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* and removing the staked amount from their balance if they are staked
* @param _user address of user
* @param _amount to check if the user can spend
* @return true if they are allowed to spend the amount being checked
*/
function allowedToTrade(address _user, uint256 _amount)
public
view
returns (bool)
{
if (
stakerDetails[_user].currentStatus != 0 &&
stakerDetails[_user].currentStatus < 5
) {
//Subtracts the stakeAmount from balance if the _user is staked
if (balanceOf(_user) - uints[_STAKE_AMOUNT] >= _amount) {
return true;
}
return false;
}
return (balanceOf(_user) >= _amount);
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param _value is the new balance
*/
function updateBalanceAtNow(address _user, uint256 _value) public {
Checkpoint[] storage checkpoints = balances[_user];
if (
checkpoints.length == 0 ||
checkpoints[checkpoints.length - 1].fromBlock != block.number
) {
checkpoints.push(
TellorStorage.Checkpoint({
fromBlock: uint128(block.number),
value: uint128(_value)
})
);
} else {
TellorStorage.Checkpoint storage oldCheckPoint =
checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
}
// SPDX-License-Identifier: MIT
/**
* This contract holds staking functions, tallyVotes and updateDisputeFee
* Because of space limitations and will be consolidated in future iterations
*/
pragma solidity 0.7.4;
import "./SafeMath.sol";
import "./TellorGetters.sol";
import "./TellorVariables.sol";
import "./Utilities.sol";
contract Extension is TellorGetters {
using SafeMath for uint256;
//emitted upon dispute tally
event DisputeVoteTallied(
uint256 indexed _disputeID,
int256 _result,
address indexed _reportedMiner,
address _reportingParty,
bool _active
);
event StakeWithdrawn(address indexed _sender); //Emits when a staker is block.timestamp no longer staked
event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period
event NewStake(address indexed _sender); //Emits upon new staker
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake() public {
newStake(msg.sender);
updateMinDisputeFee();
}
/**
* @dev This internal function is used the depositStake function to successfully stake miners.
* The function updates their status/state and status start date so they are locked it so they can't withdraw
* and updates the number of stakers in the system.
*/
function newStake(address _staker) internal {
require(
balances[_staker][balances[_staker].length - 1].value >=
uints[_STAKE_AMOUNT],
"Balance is lower than stake amount"
);
//Ensure they can only stake if they are not currently staked or if their stake time frame has ended
//and they are currently locked for withdraw
require(
stakerDetails[_staker].currentStatus == 0 ||
stakerDetails[_staker].currentStatus == 2,
"Miner is in the wrong state"
);
uints[_STAKE_COUNT] += 1;
stakerDetails[_staker] = StakeInfo({
currentStatus: 1, //this resets their stake start date to today
startDate: block.timestamp - (block.timestamp % 86400)
});
emit NewStake(_staker);
}
/*Functions*/
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the deposit
*/
function requestStakingWithdraw() public {
StakeInfo storage stakes = stakerDetails[msg.sender];
//Require that the miner is staked
require(stakes.currentStatus == 1, "Miner is not staked");
//Change the miner staked to locked to be withdrawStake
stakes.currentStatus = 2;
//Change the startDate to block.timestamp since the lock up period begins block.timestamp
//and the miner can only withdraw 7 days later from block.timestamp(check the withdraw function)
stakes.startDate = block.timestamp - (block.timestamp % 86400);
//Reduce the staker count
uints[_STAKE_COUNT] -= 1;
//Update the minimum dispute fee that is based on the number of stakers
updateMinDisputeFee();
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting
* period from request
*/
function withdrawStake() public {
StakeInfo storage stakes = stakerDetails[msg.sender];
//Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have
//passed by since they locked for withdraw
require(
block.timestamp - (block.timestamp % 86400) - stakes.startDate >=
7 days,
"7 days didn't pass"
);
require(
stakes.currentStatus == 2,
"Miner was not locked for withdrawal"
);
stakes.currentStatus = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev tallies the votes and locks the stake disbursement(currentStatus = 4) if the vote passes
* @param _disputeId is the dispute id
*/
function tallyVotes(uint256 _disputeId) public {
Dispute storage disp = disputesById[_disputeId];
//Ensure this has not already been executed/tallied
require(disp.executed == false, "Dispute has been already executed");
require(
block.timestamp >= disp.disputeUintVars[_MIN_EXECUTION_DATE],
"Time for voting haven't elapsed"
);
require(
disp.reportingParty != address(0),
"reporting Party is address 0"
);
int256 _tally = disp.tally;
if (_tally > 0) {
//Set the dispute state to passed/true
disp.disputeVotePassed = true;
}
//If the vote is not a proposed fork
if (disp.isPropFork == false) {
//Ensure the time for voting has elapsed
StakeInfo storage stakes = stakerDetails[disp.reportedMiner];
//If the vote for disputing a value is successful(disp.tally >0) then unstake the reported
// miner and transfer the stakeAmount and dispute fee to the reporting party
if (stakes.currentStatus == 3) {
stakes.currentStatus = 4;
}
}
disp.disputeUintVars[_TALLY_DATE] = block.timestamp;
disp.executed = true;
emit DisputeVoteTallied(
_disputeId,
_tally,
disp.reportedMiner,
disp.reportingParty,
disp.disputeVotePassed
);
}
/**
* @dev This function updates the minimum dispute fee as a function of the amount
* of staked miners
*/
function updateMinDisputeFee() public {
uint256 _stakeAmt = uints[_STAKE_AMOUNT];
uint256 _trgtMiners = uints[_TARGET_MINERS];
uints[_DISPUTE_FEE] = SafeMath.max(
15e18,
(_stakeAmt -
((_stakeAmt *
(SafeMath.min(_trgtMiners, uints[_STAKE_COUNT]) * 1000)) /
_trgtMiners) /
1000)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
/**
* @title Tellor Oracle Storage Library
* @dev Contains all the variables/structs used by Tellor
*/
contract TellorStorage {
//Internal struct for use in proof-of-work submission
struct Details {
uint256 value;
address miner;
}
struct Dispute {
bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp)
int256 tally; //current tally of votes for - against measure
bool executed; //is the dispute settled
bool disputeVotePassed; //did the vote pass?
bool isPropFork; //true for fork proposal NEW
address reportedMiner; //miner who submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
address proposedForkAddress; //new fork address (if fork proposal)
mapping(bytes32 => uint256) disputeUintVars;
//Each of the variables below is saved in the mapping disputeUintVars for each disputeID
//e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")]
//These are the variables saved in this mapping:
// uint keccak256("requestId");//apiID of disputed value
// uint keccak256("timestamp");//timestamp of disputed value
// uint keccak256("value"); //the value being disputed
// uint keccak256("minExecutionDate");//7 days from when dispute initialized
// uint keccak256("numberOfVotes");//the number of parties who have voted on the measure
// uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from
// uint keccak256("minerSlot"); //index in dispute array
// uint keccak256("fee"); //fee paid corresponding to dispute
mapping(address => bool) voted; //mapping of address to whether or not they voted
}
struct StakeInfo {
uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked
uint256 startDate; //stake start date
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock; // fromBlock is the block number that the value was generated from
uint128 value; // value is the amount of tokens at a specific block number
}
struct Request {
uint256[] requestTimestamps; //array of all newValueTimestamps requested
mapping(bytes32 => uint256) apiUintVars;
//Each of the variables below is saved in the mapping apiUintVars for each api request
//e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]
//These are the variables saved in this mapping:
// uint keccak256("requestQPosition"); //index in requestQ
// uint keccak256("totalTip");//bonus portion of payout
mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number
//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value
mapping(uint256 => uint256) finalValues;
mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized.
mapping(uint256 => address[5]) minersByValue;
mapping(uint256 => uint256[5]) valuesByTimestamp;
}
uint256[51] requestQ; //uint50 array of the top50 requests by payment amount
uint256[] public newValueTimestamps; //array of all timestamps requested
//Address fields in the Tellor contract are saved the addressVars mapping
//e.g. addressVars[keccak256("tellorContract")] = address
//These are the variables saved in this mapping:
// address keccak256("tellorContract");//Tellor address
// address keccak256("_owner");//Tellor Owner address
// address keccak256("_deity");//Tellor Owner that can do things at will
// address keccak256("pending_owner"); // The proposed new owner
//uint fields in the Tellor contract are saved the uintVars mapping
//e.g. uintVars[keccak256("decimals")] = uint
//These are the variables saved in this mapping:
// keccak256("decimals"); //18 decimal standard ERC20
// keccak256("disputeFee");//cost to dispute a mined value
// keccak256("disputeCount");//totalHistoricalDisputes
// keccak256("total_supply"); //total_supply of the token in circulation
// keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcoded it in...or should it be variable?)
// keccak256("stakerCount"); //number of parties currently staked
// keccak256("timeOfLastNewValue"); // time of last challenge solved
// keccak256("difficulty"); // Difficulty of current block
// keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool
// keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id
// keccak256("requestCount"); // total number of requests through the system
// keccak256("slotProgress");//Number of miners who have mined this value so far
// keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value
// keccak256("timeTarget"); //The time between blocks (mined Oracle values)
// keccak256("_tblock"); //
// keccak256("runningTips"); // VAriable to track running tips
// keccak256("currentReward"); // The current reward
// keccak256("devShare"); // The amount directed towards th devShare
// keccak256("currentTotalTips"); //
//This is a boolean that tells you if a given challenge has been completed by a given miner
mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId
mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId
mapping(uint256 => Dispute) public disputesById; //disputeId=> Dispute details
mapping(bytes32 => uint256) public requestIdByQueryHash; // api bytes32 gets an id = to count of requests array
mapping(bytes32 => uint256) public disputeIdByDisputeHash; //maps a hash to an ID for each dispute
mapping(bytes32 => mapping(address => bool)) public minersByChallenge;
Details[5] public currentMiners; //This struct is for organizing the five mined values to find the median
mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info
mapping(uint256 => Request) requestDetails;
mapping(bytes32 => uint256) public uints;
mapping(bytes32 => address) public addresses;
mapping(bytes32 => bytes32) public bytesVars;
//ERC20 storage
mapping(address => Checkpoint[]) public balances;
mapping(address => mapping(address => uint256)) public _allowances;
//Migration storage
mapping(address => bool) public migrated;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
// Helper contract to store hashes of variables
contract TellorVariables {
bytes32 constant _BLOCK_NUMBER =
0x4b4cefd5ced7569ef0d091282b4bca9c52a034c56471a6061afd1bf307a2de7c; //keccak256("_BLOCK_NUMBER");
bytes32 constant _CURRENT_CHALLENGE =
0xd54702836c9d21d0727ffacc3e39f57c92b5ae0f50177e593bfb5ec66e3de280; //keccak256("_CURRENT_CHALLENGE");
bytes32 constant _CURRENT_REQUESTID =
0xf5126bb0ac211fbeeac2c0e89d4c02ac8cadb2da1cfb27b53c6c1f4587b48020; //keccak256("_CURRENT_REQUESTID");
bytes32 constant _CURRENT_REWARD =
0xd415862fd27fb74541e0f6f725b0c0d5b5fa1f22367d9b78ec6f61d97d05d5f8; //keccak256("_CURRENT_REWARD");
bytes32 constant _CURRENT_TOTAL_TIPS =
0x09659d32f99e50ac728058418d38174fe83a137c455ff1847e6fb8e15f78f77a; //keccak256("_CURRENT_TOTAL_TIPS");
bytes32 constant _DEITY =
0x5fc094d10c65bc33cc842217b2eccca0191ff24148319da094e540a559898961; //keccak256("_DEITY");
bytes32 constant _DIFFICULTY =
0xf758978fc1647996a3d9992f611883adc442931dc49488312360acc90601759b; //keccak256("_DIFFICULTY");
bytes32 constant _DISPUTE_COUNT =
0x310199159a20c50879ffb440b45802138b5b162ec9426720e9dd3ee8bbcdb9d7; //keccak256("_DISPUTE_COUNT");
bytes32 constant _DISPUTE_FEE =
0x675d2171f68d6f5545d54fb9b1fb61a0e6897e6188ca1cd664e7c9530d91ecfc; //keccak256("_DISPUTE_FEE");
bytes32 constant _DISPUTE_ROUNDS =
0x6ab2b18aafe78fd59c6a4092015bddd9fcacb8170f72b299074f74d76a91a923; //keccak256("_DISPUTE_ROUNDS");
bytes32 constant _EXTENSION =
0x2b2a1c876f73e67ebc4f1b08d10d54d62d62216382e0f4fd16c29155818207a4; //keccak256("_EXTENSION");
bytes32 constant _FEE =
0x1da95f11543c9b03927178e07951795dfc95c7501a9d1cf00e13414ca33bc409; //keccak256("FEE");
bytes32 constant _MIGRATOR =
0xc6b005d45c4c789dfe9e2895b51df4336782c5ff6bd59a5c5c9513955aa06307; //keccak256("_MIGRATOR");
bytes32 constant _MIN_EXECUTION_DATE =
0x46f7d53798d31923f6952572c6a19ad2d1a8238d26649c2f3493a6d69e425d28; //keccak256("_MIN_EXECUTION_DATE");
bytes32 constant _MINER_SLOT =
0x6de96ee4d33a0617f40a846309c8759048857f51b9d59a12d3c3786d4778883d; //keccak256("_MINER_SLOT");
bytes32 constant _NUM_OF_VOTES =
0x1da378694063870452ce03b189f48e04c1aa026348e74e6c86e10738514ad2c4; //keccak256("_NUM_OF_VOTES");
bytes32 constant _OLD_TELLOR =
0x56e0987db9eaec01ed9e0af003a0fd5c062371f9d23722eb4a3ebc74f16ea371; //keccak256("_OLD_TELLOR");
bytes32 constant _ORIGINAL_ID =
0xed92b4c1e0a9e559a31171d487ecbec963526662038ecfa3a71160bd62fb8733; //keccak256("_ORIGINAL_ID");
bytes32 constant _OWNER =
0x7a39905194de50bde334d18b76bbb36dddd11641d4d50b470cb837cf3bae5def; //keccak256("_OWNER");
bytes32 constant _PAID =
0x29169706298d2b6df50a532e958b56426de1465348b93650fca42d456eaec5fc; //keccak256("_PAID");
bytes32 constant _PENDING_OWNER =
0x7ec081f029b8ac7e2321f6ae8c6a6a517fda8fcbf63cabd63dfffaeaafa56cc0; //keccak256("_PENDING_OWNER");
bytes32 constant _REQUEST_COUNT =
0x3f8b5616fa9e7f2ce4a868fde15c58b92e77bc1acd6769bf1567629a3dc4c865; //keccak256("_REQUEST_COUNT");
bytes32 constant _REQUEST_ID =
0x9f47a2659c3d32b749ae717d975e7962959890862423c4318cf86e4ec220291f; //keccak256("_REQUEST_ID");
bytes32 constant _REQUEST_Q_POSITION =
0xf68d680ab3160f1aa5d9c3a1383c49e3e60bf3c0c031245cbb036f5ce99afaa1; //keccak256("_REQUEST_Q_POSITION");
bytes32 constant _SLOT_PROGRESS =
0xdfbec46864bc123768f0d134913175d9577a55bb71b9b2595fda21e21f36b082; //keccak256("_SLOT_PROGRESS");
bytes32 constant _STAKE_AMOUNT =
0x5d9fadfc729fd027e395e5157ef1b53ef9fa4a8f053043c5f159307543e7cc97; //keccak256("_STAKE_AMOUNT");
bytes32 constant _STAKE_COUNT =
0x10c168823622203e4057b65015ff4d95b4c650b308918e8c92dc32ab5a0a034b; //keccak256("_STAKE_COUNT");
bytes32 constant _T_BLOCK =
0xf3b93531fa65b3a18680d9ea49df06d96fbd883c4889dc7db866f8b131602dfb; //keccak256("_T_BLOCK");
bytes32 constant _TALLY_DATE =
0xf9e1ae10923bfc79f52e309baf8c7699edb821f91ef5b5bd07be29545917b3a6; //keccak256("_TALLY_DATE");
bytes32 constant _TARGET_MINERS =
0x0b8561044b4253c8df1d9ad9f9ce2e0f78e4bd42b2ed8dd2e909e85f750f3bc1; //keccak256("_TARGET_MINERS");
bytes32 constant _TELLOR_CONTRACT =
0x0f1293c916694ac6af4daa2f866f0448d0c2ce8847074a7896d397c961914a08; //keccak256("_TELLOR_CONTRACT");
bytes32 constant _TELLOR_GETTERS =
0xabd9bea65759494fe86471c8386762f989e1f2e778949e94efa4a9d1c4b3545a; //keccak256("_TELLOR_GETTERS");
bytes32 constant _TIME_OF_LAST_NEW_VALUE =
0x2c8b528fbaf48aaf13162a5a0519a7ad5a612da8ff8783465c17e076660a59f1; //keccak256("_TIME_OF_LAST_NEW_VALUE");
bytes32 constant _TIME_TARGET =
0xd4f87b8d0f3d3b7e665df74631f6100b2695daa0e30e40eeac02172e15a999e1; //keccak256("_TIME_TARGET");
bytes32 constant _TIMESTAMP =
0x2f9328a9c75282bec25bb04befad06926366736e0030c985108445fa728335e5; //keccak256("_TIMESTAMP");
bytes32 constant _TOTAL_SUPPLY =
0xe6148e7230ca038d456350e69a91b66968b222bfac9ebfbea6ff0a1fb7380160; //keccak256("_TOTAL_SUPPLY");
bytes32 constant _TOTAL_TIP =
0x1590276b7f31dd8e2a06f9a92867333eeb3eddbc91e73b9833e3e55d8e34f77d; //keccak256("_TOTAL_TIP");
bytes32 constant _VALUE =
0x9147231ab14efb72c38117f68521ddef8de64f092c18c69dbfb602ffc4de7f47; //keccak256("_VALUE");
bytes32 constant _EIP_SLOT =
0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
} | Retrieve value from oracle based on timestamp _requestId being requested _timestamp to retrieve data/value from return value for timestamp submitted/ | function retrieveData(uint256 _requestId, uint256 _timestamp)
public
view
returns (uint256)
{
return requestDetails[_requestId].finalValues[_timestamp];
}
| 6,847,376 |
./full_match/56/0xE2935D78421A9ED772A70FF2AF7907237D9Fe013/sources/project_/contracts/TokenPreSale.sol | To update the sale times _id Presale id to update _startTime New start time _endTime New end time/ | function changeSaleTimes(
uint256 _id,
uint256 _startTime,
uint256 _endTime
) external checkPresaleId(_id) onlyOwner {
require(_startTime > 0 || _endTime > 0, "Invalid parameters");
if (_startTime > 0) {
require(
block.timestamp < presale[_id].startTime,
"Sale already started"
);
require(block.timestamp < _startTime, "Sale time in past");
uint256 prevValue = presale[_id].startTime;
presale[_id].startTime = _startTime;
emit PresaleUpdated(
bytes32("START"),
prevValue,
_startTime,
block.timestamp
);
}
if (_endTime > 0) {
require(
block.timestamp < presale[_id].endTime,
"Sale already ended"
);
require(_endTime > presale[_id].startTime, "Invalid endTime");
uint256 prevValue = presale[_id].endTime;
presale[_id].endTime = _endTime;
emit PresaleUpdated(
bytes32("END"),
prevValue,
_endTime,
block.timestamp
);
}
}
| 3,240,555 |
pragma solidity >=0.5.0 <0.6.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address payable public _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address payable newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface Token {
function transfer(address to, uint256 value) external returns (bool);
function balanceOf(address who) external view returns (uint256);
}
contract Buy_VIR_Token is Ownable{
using SafeMath for uint;
address public tokenAddr;
uint256 private ethAmount;
uint256 public tokenPriceEth = 22000000000000;
uint256 public tokenDecimal = 18;
uint256 public ethDecimal = 18;
event TokenTransfer(address beneficiary, uint amount);
mapping (address => uint256) public balances;
mapping(address => uint256) public tokenExchanged;
constructor(address _tokenAddr) public {
tokenAddr = _tokenAddr;
}
function() payable external {
ExchangeETHforToken(msg.sender, msg.value);
balances[msg.sender] = balances[msg.sender].add(msg.value);
}
function ExchangeETHforToken(address _addr, uint256 _amount) private {
uint256 amount = _amount;
address userAdd = _addr;
ethAmount = ((amount.mul(10 ** uint256(tokenDecimal)).div(tokenPriceEth)).mul(10 ** uint256(tokenDecimal))).div(10 ** uint256(tokenDecimal));
require(Token(tokenAddr).balanceOf(address(this)) >= ethAmount, "There is low token balance in contract");
require(Token(tokenAddr).transfer(userAdd, ethAmount));
emit TokenTransfer(userAdd, ethAmount);
tokenExchanged[msg.sender] = tokenExchanged[msg.sender].add(ethAmount);
_owner.transfer(amount);
}
function ExchangeETHforTokenMannual() public payable {
uint256 amount = msg.value;
address userAdd = msg.sender;
ethAmount = ((amount.mul(10 ** uint256(tokenDecimal)).div(tokenPriceEth)).mul(10 ** uint256(tokenDecimal))).div(10 ** uint256(tokenDecimal));
require(Token(tokenAddr).balanceOf(address(this)) >= ethAmount, "There is low token balance in contract");
require(Token(tokenAddr).transfer(userAdd, ethAmount));
balances[msg.sender] = balances[msg.sender].add(msg.value);
emit TokenTransfer(userAdd, ethAmount);
tokenExchanged[msg.sender] = tokenExchanged[msg.sender].add(ethAmount);
_owner.transfer(amount);
}
function updateTokenPrice(uint256 newTokenValue) public onlyOwner {
tokenPriceEth = newTokenValue;
}
function updateTokenDecimal(uint256 newDecimal) public onlyOwner {
tokenDecimal = newDecimal;
}
function updateTokenAddress(address newTokenAddr) public onlyOwner {
tokenAddr = newTokenAddr;
}
function withdrawTokens(address beneficiary) public onlyOwner {
require(Token(tokenAddr).transfer(beneficiary, Token(tokenAddr).balanceOf(address(this))));
}
function withdrawCrypto(address payable beneficiary) public onlyOwner {
beneficiary.transfer(address(this).balance);
}
function tokenBalance() public view returns (uint256){
return Token(tokenAddr).balanceOf(address(this));
}
function ethBalance() public view returns (uint256){
return address(this).balance;
}
} | Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./ | function transferOwnership(address payable newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 497,359 |
./full_match/11155111/0x945217B1bA47Ad0834e838ae173FB8B4B9135314/sources/src/RepoDriver.sol | Returns the RepoDriver storage specific to AnyApi. return storageRef The storage. slither-disable-next-line assembly | function _repoDriverAnyApiStorage()
internal
view
returns (RepoDriverAnyApiStorage storage storageRef)
{
bytes32 slot = _repoDriverAnyApiStorageSlot;
assembly {
storageRef.slot := slot
}
}
| 3,820,046 |
// SPDX-License-Identifier: MIT
// File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol
pragma solidity >=0.5.0;
interface ILayerZeroUserApplicationConfig {
// @notice set the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _configType - type of configuration. every messaging library has its own convention.
// @param _config - configuration in the bytes. can encode arbitrary content.
function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
// @notice set the send() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setSendVersion(uint16 _version) external;
// @notice set the lzReceive() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setReceiveVersion(uint16 _version) external;
// @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
// @param _srcChainId - the chainId of the source chain
// @param _srcAddress - the contract address of the source contract at the source chain
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
}
// File: contracts/interfaces/ILayerZeroEndpoint.sol
pragma solidity >=0.5.0;
interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
// @notice send a LayerZero message to the specified address at a LayerZero endpoint.
// @param _dstChainId - the destination chain identifier
// @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
// @param _payload - a custom bytes payload to send to the destination contract
// @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
// @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
// @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
// @notice used by the messaging library to publish verified payload
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source contract (as bytes) at the source chain
// @param _dstAddress - the address on destination chain
// @param _nonce - the unbound message ordering nonce
// @param _gasLimit - the gas limit for external contract execution
// @param _payload - verified payload to send to the destination contract
function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
// @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
// @notice get the outboundNonce from this source chain which, consequently, is always an EVM
// @param _srcAddress - the source chain contract address
function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
// @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
// @param _dstChainId - the destination chain identifier
// @param _userApplication - the user app address on this EVM chain
// @param _payload - the custom message to send over LayerZero
// @param _payInZRO - if false, user app pays the protocol fee in native token
// @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
// @notice get this Endpoint's immutable source identifier
function getChainId() external view returns (uint16);
// @notice the interface to retry failed message on this Endpoint destination
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
// @param _payload - the payload to be retried
function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
// @notice query if any STORED payload (message blocking) at the endpoint.
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
// @notice query if the _libraryAddress is valid for sending msgs.
// @param _userApplication - the user app address on this EVM chain
function getSendLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the _libraryAddress is valid for receiving msgs.
// @param _userApplication - the user app address on this EVM chain
function getReceiveLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the non-reentrancy guard for send() is on
// @return true if the guard is on. false otherwise
function isSendingPayload() external view returns (bool);
// @notice query if the non-reentrancy guard for receive() is on
// @return true if the guard is on. false otherwise
function isReceivingPayload() external view returns (bool);
// @notice get the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _userApplication - the contract address of the user application
// @param _configType - type of configuration. every messaging library has its own convention.
function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
// @notice get the send() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getSendVersion(address _userApplication) external view returns (uint16);
// @notice get the lzReceive() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getReceiveVersion(address _userApplication) external view returns (uint16);
}
// File: contracts/interfaces/ILayerZeroReceiver.sol
pragma solidity >=0.5.0;
interface ILayerZeroReceiver {
// @notice LayerZero endpoint will invoke this function to deliver the message on the destination
// @param _srcChainId - the source endpoint identifier
// @param _srcAddress - the source sending contract address from the source chain
// @param _nonce - the ordered message nonce
// @param _payload - the signed payload is the UA bytes has encoded to be sent
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
}
// 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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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;
}
}
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);
}
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// 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);
}
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
pragma solidity ^0.8.0;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
string public uriSuffix = ".json";
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/NonblockingReceiver.sol
pragma solidity ^0.8.6;
abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver {
ILayerZeroEndpoint internal endpoint;
struct FailedMessages {
uint payloadLength;
bytes32 payloadHash;
}
mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages;
mapping(uint16 => bytes) public trustedRemoteLookup;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload);
function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override {
require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security
require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]),
"NonblockingReceiver: invalid source sending contract");
// try-catch all errors/exceptions
// having failed messages does not block messages passing
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload));
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public {
// only internal transaction
require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge.");
// handle incoming message
_LzReceive( _srcChainId, _srcAddress, _nonce, _payload);
}
// abstract function
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal;
function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal {
endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam);
}
function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable {
// assert there is message to retry
FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce];
require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message");
require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload");
// clear the stored message
failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
// execute the message. revert if it fails again
this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner {
trustedRemoteLookup[_chainId] = _trustedRemote;
}
}
pragma solidity ^0.8.7;
contract OmniAmongPunks is Ownable, ERC721A, NonblockingReceiver {
using Strings for uint256;
address public _owner;
uint256 nextTokenId = 0;
uint256 MAX_NETWORK_MINT = 0;
uint256 private price = 0;
uint256 public freeMintAmount = 0;
string public hiddenMetadataUri;
string private baseURI;
bool public saleOpen = true;
bool public revealed = false;
event Minted(uint256 totalMinted);
uint gasForDestinationLzReceive = 350000;
constructor(string memory hiddenMetadataUri_, string memory baseURI_, address _layerZeroEndpoint, uint256 _nextTokenId, uint256 _maxTokenId, uint256 _price, uint256 _freeMint) ERC721A("OmniAmongPunks", "AP") {
_owner = msg.sender;
endpoint = ILayerZeroEndpoint(_layerZeroEndpoint);
baseURI = baseURI_;
hiddenMetadataUri = hiddenMetadataUri_;
nextTokenId = _nextTokenId;
MAX_NETWORK_MINT = _maxTokenId;
price = _price;
freeMintAmount = _freeMint;
}
// mint function
function mint(address _to, uint256 numTokens) external payable {
require(nextTokenId + numTokens <= MAX_NETWORK_MINT, "Exceeds maximum supply");
require(numTokens > 0, "Minimum 1 NFT has to be minted per transaction");
if (msg.sender != owner() && (nextTokenId + numTokens) > freeMintAmount) {
require(saleOpen, "Sale is not open yet");
require(
msg.value >= price * numTokens,
"Ether sent with this transaction is not correct"
);
}
if(msg.sender != owner()) {
require(
numTokens <= 5,
"Maximum 5 NFTs can be minted per transaction"
);
}
nextTokenId += numTokens;
_safeMint(_to, numTokens);
emit Minted(numTokens);
}
// This function transfers the nft from your address on the
// source chain to the same address on the destination chain
function traverseChains(uint16 _chainId, uint tokenId) public payable {
require(msg.sender == ownerOf(tokenId), "You must own the token to traverse");
require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel");
// burn NFT, eliminating it from circulation on src chain
_burn(tokenId);
// abi.encode() the payload with the values to send
bytes memory payload = abi.encode(msg.sender, tokenId);
// encode adapterParams to specify more gas for the destination
uint16 version = 1;
bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive);
// get the fees we need to pay to LayerZero + Relayer to cover message delivery
// you will be refunded for extra gas paid
(uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams);
require(msg.value >= messageFee, "GG: msg.value not enough to cover messageFee. Send gas for message fees");
endpoint.send{value: msg.value}(
_chainId, // destination chainId
trustedRemoteLookup[_chainId], // destination address of nft contract
payload, // abi.encoded()'ed bytes
payable(msg.sender), // refund address
address(0x0), // 'zroPaymentAddress' unused for this
adapterParams // txParameters
);
}
function setBaseURI(string memory URI) external onlyOwner {
baseURI = URI;
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function donate() external payable {
// thank you
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
if (revealed == false) {
return hiddenMetadataUri;
}
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
// This allows the devs to receive kind donations
function withdraw(uint amt) external onlyOwner {
(bool sent, ) = payable(_owner).call{value: amt}("");
require(sent, "GG: Failed to withdraw Ether");
}
// just in case this fixed variable limits us from future integrations
function setGasForDestinationLzReceive(uint newVal) external onlyOwner {
gasForDestinationLzReceive = newVal;
}
// ------------------
// Internal Functions
// ------------------
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal {
// decode
(address toAddr, uint tokenId) = abi.decode(_payload, (address, uint));
//mint the tokens back into existence on destination chain
_safeMint(toAddr, tokenId);
}
function _baseURI() override internal view returns (string memory) {
return baseURI;
}
} | ERC-721 Non-Fungible Token Standard, optional metadata extension/ | interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
}
| 14,599,783 |
// File: contracts/tokens/ERC20.sol
pragma solidity 0.5.14;
contract ERC20 {
function TOTALSUPPLY679() public view returns (uint256 supply); //inject NONSTANDARD NAMING
function BALANCEOF603(address _owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING
function TRANSFER978(address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM476(address _from, address _to, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function APPROVE644(address _spender, uint256 _value) public returns (bool success); //inject NONSTANDARD NAMING
function ALLOWANCE384(address _owner, address _spender) public view returns (uint256 remaining); //inject NONSTANDARD NAMING
event TRANSFER760(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL643(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/tokens/SafeMath.sol
pragma solidity 0.5.14;
library SafeMath {
function MUL81(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 DIV451(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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;
}
function SUB832(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function ADD114(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function MOD487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: contracts/tokens/StandardToken.sol
pragma solidity 0.5.14;
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) private allowed;
uint256 internal totalSupply_;
function TOTALSUPPLY679() public view returns (uint256) { //inject NONSTANDARD NAMING
return totalSupply_;
}
function BALANCEOF603(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return balances[_owner];
}
function ALLOWANCE384(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowed[_owner][_spender];
}
function TRANSFER978(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].SUB832(_value);
balances[_to] = balances[_to].ADD114(_value);
emit TRANSFER760(msg.sender, _to, _value);
return true;
}
function APPROVE644(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = _value;
emit APPROVAL643(msg.sender, _spender, _value);
return true;
}
function TRANSFERFROM476(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].SUB832(_value);
balances[_to] = balances[_to].ADD114(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB832(_value);
emit TRANSFER760(_from, _to, _value);
return true;
}
function INCREASEAPPROVAL847(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].ADD114(_addedValue));
emit APPROVAL643(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function DECREASEAPPROVAL982(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.SUB832(_subtractedValue);
}
emit APPROVAL643(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function _MINT883(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0));
totalSupply_ = totalSupply_.ADD114(_amount);
balances[_account] = balances[_account].ADD114(_amount);
emit TRANSFER760(address(0), _account, _amount);
}
function _BURN950(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0));
require(_amount <= balances[_account]);
totalSupply_ = totalSupply_.SUB832(_amount);
balances[_account] = balances[_account].SUB832(_amount);
emit TRANSFER760(_account, address(0), _amount);
}
function _BURNFROM531(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_amount <= allowed[_account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_account][msg.sender] = allowed[_account][msg.sender].SUB832(_amount);
_BURN950(_account, _amount);
}
}
// File: contracts/tokens/Ownable.sol
pragma solidity 0.5.14;
contract Ownable {
address public owner;
event OWNERSHIPRENOUNCED53(address indexed previousOwner); //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED268( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier ONLYOWNER709() { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function RENOUNCEOWNERSHIP918() public ONLYOWNER709 { //inject NONSTANDARD NAMING
emit OWNERSHIPRENOUNCED53(owner);
owner = address(0);
}
function TRANSFEROWNERSHIP47(address _newOwner) public ONLYOWNER709 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP390(_newOwner);
}
function _TRANSFEROWNERSHIP390(address _newOwner) internal { //inject NONSTANDARD NAMING
require(_newOwner != address(0));
emit OWNERSHIPTRANSFERRED268(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/tokens/BurnableToken.sol
pragma solidity 0.5.14;
contract BurnableToken is StandardToken {
event BURN276(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN42(uint256 _value) public { //inject NONSTANDARD NAMING
_BURN950(msg.sender, _value);
}
function BURNFROM69(address _from, uint256 _value) public { //inject NONSTANDARD NAMING
_BURNFROM531(_from, _value);
}
function _BURN950(address _who, uint256 _value) internal { //inject NONSTANDARD NAMING
super._BURN950(_who, _value);
emit BURN276(_who, _value);
}
}
// File: contracts/tokens/SportValueCoin.sol
pragma solidity 0.5.14;
contract SportValueCoin is BurnableToken {
// meta data
string public constant symbol15 = "SVC"; //inject NONSTANDARD NAMING
string public version = '1.0';
string public constant name455 = "Sport Value Coin"; //inject NONSTANDARD NAMING
uint256 public constant decimals291 = 18; //inject NONSTANDARD NAMING
uint256 public constant initial_supply658 = 100 * (10 ** 6) * 10 ** decimals291; // 100 millions //inject NONSTANDARD NAMING
constructor() public {
_MINT883(msg.sender, initial_supply658);
}
} | inject NONSTANDARD NAMING | function SUB832(uint256 _a, uint256 _b) internal pure returns (uint256) { | 12,906,829 |
./partial_match/42/0x4ffADC639B57e864150ff98a55D249fed53fa63B/sources/ZuniBadge.sol | Create a new Smart Pool Initialize the swap fee to the value provided in the CRP constructor Can be changed if the canChangeSwapFee permission is enabled initialSupply starting token balance/ If the controller can change the cap, initialize it to the initial supply Defensive programming, so that there is no gap between creating the pool (initialized to unlimited in the constructor), and setting the cap, which they will presumably do if they have this right. Modifying state variable after external calls here, but not essential, so not dangerous | function createPoolInternal(uint256 initialSupply) internal {
require(address(bPool) == address(0), "ERR_IS_CREATED");
require(
initialSupply >= BalancerConstants.MIN_POOL_SUPPLY,
"ERR_INIT_SUPPLY_MIN"
);
require(
initialSupply <= BalancerConstants.MAX_POOL_SUPPLY,
"ERR_INIT_SUPPLY_MAX"
);
if (rights.canChangeCap) {
bspCap = initialSupply;
}
_pushPoolShare(msg.sender, initialSupply);
require(BalancerConstants.EXIT_FEE == 0, "ERR_NONZERO_EXIT_FEE");
for (uint256 i = 0; i < _initialTokens.length; i++) {
address t = _initialTokens[i];
uint256 bal = _initialBalances[i];
uint256 denorm = gradualUpdate.startWeights[i];
bool returnValue = IERC20(t).transferFrom(
msg.sender,
address(this),
bal
);
require(returnValue, "ERR_ERC20_FALSE");
returnValue = IERC20(t).safeApprove(
address(bPool),
BalancerConstants.MAX_UINT
);
require(returnValue, "ERR_ERC20_FALSE");
bPool.bind(t, bal, denorm);
}
while (_initialTokens.length > 0) {
_initialTokens.pop();
}
bPool.setPublicSwap(true);
}
| 3,449,043 |
./full_match/137/0xfe672A4b063b1895b2f6531a78a69c014614B2D8/sources/contracts/migrations/old/IPeronioV1.sol | Markup Initialization can only be run once Roles Events | interface IPeronioV1 {
function USDC_ADDRESS() external view returns (address);
function MAI_ADDRESS() external view returns (address);
function LP_ADDRESS() external view returns (address);
function QUICKSWAP_ROUTER_ADDRESS() external view returns (address);
function QIDAO_FARM_ADDRESS() external view returns (address);
function QI_ADDRESS() external view returns (address);
function QIDAO_POOL_ID() external view returns (uint256);
function MARKUP_DECIMALS() external view returns (uint8);
function markup() external view returns (uint256);
function swapFee() external view returns (uint256);
function initialized() external view returns (bool);
function MARKUP_ROLE() external view returns (bytes32);
function REWARDS_ROLE() external view returns (bytes32);
event Initialized(address owner, uint256 collateral, uint256 startingRatio);
event Minted(address indexed to, uint256 collateralAmount, uint256 tokenAmount);
event Withdrawal(address indexed to, uint256 collateralAmount, uint256 tokenAmount);
event MarkupUpdated(address operator, uint256 markup);
event CompoundRewards(uint256 qi, uint256 usdc, uint256 lp);
event HarvestedMatic(uint256 wmatic, uint256 collateral);
function decimals() external view returns (uint8);
function initialize(uint256 usdcAmount, uint256 startingRatio) external;
function setMarkup(uint256 markup_) external;
function mint(
address to,
uint256 usdcAmount,
uint256 minReceive
) external returns (uint256 peAmount);
function withdraw(address to, uint256 peAmount) external;
function claimRewards() external;
function compoundRewards() external returns (uint256 usdcAmount, uint256 lpAmount);
function stakedBalance() external view returns (uint256);
function stakedValue() external view returns (uint256 totalUSDC);
function usdcPrice() external view returns (uint256);
function buyingPrice() external view returns (uint256);
function collateralRatio() external view returns (uint256);
function getPendingRewardsAmount() external view returns (uint256 amount);
function getLpReserves() external view returns (uint112 usdcReserves, uint112 maiReserves);
pragma solidity ^0.8.17;
}
| 4,733,905 |
./full_match/8453/0x3D2673a5a253052bF2b46EbB70da77876Cd085ac/sources/contracts/lendingpool/ExtraInterestBearingToken.sol | Mints `amount` eTokens to `user`, only the LendingPool Contract can call this function. user The address receiving the minted tokens amount The amount of tokens getting minted/ | function mint(
address user,
uint256 amount
) external onlyLendingPool nonReentrant {
_mint(user, amount);
emit Mint(user, amount);
}
| 11,556,861 |
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity 0.5.17;
library Math {
function MAX311(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN896(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE467(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity 0.5.17;
library SafeMath {
function ADD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB912(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB912(a, b, "SafeMath: subtraction overflow");
}
function SUB912(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 MUL612(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 DIV645(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV645(a, b, "SafeMath: division by zero");
}
function DIV645(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 MOD528(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD528(a, b, "SafeMath: modulo by zero");
}
function MOD528(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity 0.5.17;
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal {}
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER219() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA337() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this;
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity 0.5.17;
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED705(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER219();
emit OWNERSHIPTRANSFERRED705(address(0), _owner);
}
function OWNER858() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER527() { //inject NONSTANDARD NAMING
require(ISOWNER429(), "Ownable: caller is not the owner");
_;
}
function ISOWNER429() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER219() == _owner;
}
function RENOUNCEOWNERSHIP633() public ONLYOWNER527 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED705(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP10(address newOwner) public ONLYOWNER527 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP120(newOwner);
}
function _TRANSFEROWNERSHIP120(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED705(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity 0.5.17;
interface IERC20 {
function TOTALSUPPLY2() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF265(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER164(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function MINT263(address account, uint amount) external; //inject NONSTANDARD NAMING
function BURN805(uint amount) external; //inject NONSTANDARD NAMING
function ALLOWANCE538(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE42(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM15(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function MINTERS951(address account) external view returns (bool); //inject NONSTANDARD NAMING
event TRANSFER380(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL481(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity 0.5.17;
library Address {
function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {codehash := extcodehash(account)}
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE864(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE732(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");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity 0.5.17;
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER450(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFER164.selector, to, value));
}
function SAFETRANSFERFROM145(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFERFROM15.selector, from, to, value));
}
function SAFEAPPROVE302(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.ALLOWANCE538(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, value));
}
function SAFEINCREASEALLOWANCE445(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE538(address(this), spender).ADD124(value);
CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE538(address(this), spender).SUB912(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN337(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).ISCONTRACT794(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/IRewardDistributionRecipient.sol
pragma solidity 0.5.17;
contract IRewardDistributionRecipient is Ownable {
address public rewardReferral;
function NOTIFYREWARDAMOUNT832(uint256 reward) external; //inject NONSTANDARD NAMING
function SETREWARDREFERRAL334(address _rewardReferral) external ONLYOWNER527 { //inject NONSTANDARD NAMING
rewardReferral = _rewardReferral;
}
}
// File: contracts/CurveRewards.sol
pragma solidity 0.5.17;
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
IERC20 public yfv = IERC20(0x45f24BaEef268BB6d63AEe5129015d69702BCDfa);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function TOTALSUPPLY2() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF265(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TOKENSTAKE952(uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.ADD124(actualStakeAmount);
_balances[msg.sender] = _balances[msg.sender].ADD124(actualStakeAmount);
yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount);
}
function TOKENSTAKEONBEHALF333(address stakeFor, uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.ADD124(actualStakeAmount);
_balances[stakeFor] = _balances[stakeFor].ADD124(actualStakeAmount);
yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount);
}
function TOKENWITHDRAW537(uint256 amount, uint256 actualWithdrawAmount) internal { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.SUB912(amount);
_balances[msg.sender] = _balances[msg.sender].SUB912(amount);
yfv.SAFETRANSFER450(msg.sender, actualWithdrawAmount);
}
}
interface IYFVReferral {
function SETREFERRER414(address farmer, address referrer) external; //inject NONSTANDARD NAMING
function GETREFERRER855(address farmer) external view returns (address); //inject NONSTANDARD NAMING
}
contract YFVStakeV2 is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public vUSD = IERC20(0x1B8E12F839BD4e73A47adDF76cF7F0097d74c14C);
IERC20 public vETH = IERC20(0x76A034e76Aa835363056dd418611E4f81870f16e);
uint256 public vETH_REWARD_FRACTION_RATE = 1000;
uint256 public constant duration178 = 7 days; //inject NONSTANDARD NAMING
uint8 public constant number_epochs944 = 38; //inject NONSTANDARD NAMING
uint256 public constant referral_commission_percent277 = 1; //inject NONSTANDARD NAMING
uint256 public currentEpochReward = 0;
uint256 public totalAccumulatedReward = 0;
uint8 public currentEpoch = 0;
uint256 public starttime = 1598968800; // Tuesday, September 1, 2020 2:00:00 PM (GMT+0)
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public constant default_epoch_reward278 = 230000 * (10 ** 9); // 230,000 vUSD (and 230 vETH) //inject NONSTANDARD NAMING
uint256 public constant total_reward44 = default_epoch_reward278 * number_epochs944; // 8,740,000 vUSD (and 8,740 vETH) //inject NONSTANDARD NAMING
uint256 public epochReward = default_epoch_reward278;
uint256 public minStakingAmount = 90 ether;
uint256 public unstakingFrozenTime = 40 hours;
// ** DISABLED AT BEGINNING - WILL SET IT BY GOVERNANCE AFTER VIP-1.1
// ** unlockWithdrawFee = 0.1%: stakers will need to pay 0.1% (sent to insurance fund)of amount they want to withdraw if the coin still frozen
// ** lowStakeDepositFee = 0.1%: stakers still can stake with low amount but need to pay 0.1% (sent to insurance fund)
// specially, if lowStakeDepositFee = 10000 -> low amount stakers will not pay anything (richmen pay tax, not poormen)
// ** highStakeDepositFee = 0.1%: stakers need to pay 0.1% of extra amount more than 90 YFV (sent to insurance fund)
uint256 public lowStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%)
uint256 public highStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%)
uint256 public unlockWithdrawFee = 0; // per ten thousand (eg. 15 -> 0.15%)
address public yfvInsuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
mapping(address => uint256) public lastStakeTimes;
mapping(address => uint256) public accumulatedStakingPower; // will accumulate every time staker does getReward()
mapping(address => bool) public whitelistedPools; // for stake on behalf
event REWARDADDED885(uint256 reward); //inject NONSTANDARD NAMING
event YFVREWARDADDED261(uint256 reward); //inject NONSTANDARD NAMING
event BURNED28(uint256 reward); //inject NONSTANDARD NAMING
event STAKED939(address indexed user, uint256 amount, uint256 actualStakeAmount); //inject NONSTANDARD NAMING
event WITHDRAWN649(address indexed user, uint256 amount, uint256 actualWithdrawAmount); //inject NONSTANDARD NAMING
event REWARDPAID896(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
event COMMISSIONPAID234(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
constructor() public {
whitelistedPools[0x62a9fE913eb596C8faC0936fd2F51064022ba22e] = true; // BAL Pool
whitelistedPools[0x70b83A7f5E83B3698d136887253E0bf426C9A117] = true; // YFI Pool
whitelistedPools[0x1c990fC37F399C935625b815975D0c9fAD5C31A1] = true; // BAT Pool
whitelistedPools[0x752037bfEf024Bd2669227BF9068cb22840174B0] = true; // REN Pool
whitelistedPools[0x9b74774f55C0351fD064CfdfFd35dB002C433092] = true; // KNC Pool
whitelistedPools[0xFBDE07329FFc9Ec1b70f639ad388B94532b5E063] = true; // BTC Pool
whitelistedPools[0x67FfB615EAEb8aA88fF37cCa6A32e322286a42bb] = true; // ETH Pool
whitelistedPools[0x196CF719251579cBc850dED0e47e972b3d7810Cd] = true; // LINK Pool
whitelistedPools[msg.sender] = true; // to be able to stakeOnBehalf farmer who have stucked fund in Pool Stake v1.
}
function ADDWHITELISTEDPOOL116(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING
whitelistedPools[_addressPool] = true;
}
function REMOVEWHITELISTEDPOOL972(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING
whitelistedPools[_addressPool] = false;
}
function SETYFVINSURANCEFUND27(address _yfvInsuranceFund) public ONLYOWNER527 { //inject NONSTANDARD NAMING
yfvInsuranceFund = _yfvInsuranceFund;
}
function SETEPOCHREWARD899(uint256 _epochReward) public ONLYOWNER527 { //inject NONSTANDARD NAMING
require(_epochReward <= default_epoch_reward278 * 10, "Insane big _epochReward!"); // At most 10x only
epochReward = _epochReward;
}
function SETMINSTAKINGAMOUNT151(uint256 _minStakingAmount) public ONLYOWNER527 { //inject NONSTANDARD NAMING
minStakingAmount = _minStakingAmount;
}
function SETUNSTAKINGFROZENTIME482(uint256 _unstakingFrozenTime) public ONLYOWNER527 { //inject NONSTANDARD NAMING
unstakingFrozenTime = _unstakingFrozenTime;
}
function SETSTAKEDEPOSITFEE451(uint256 _lowStakeDepositFee, uint256 _highStakeDepositFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING
require(_lowStakeDepositFee <= 100 || _lowStakeDepositFee == 10000, "Dont be too greedy"); // <= 1% OR set to 10000 to disable low stake fee
require(_highStakeDepositFee <= 100, "Dont be too greedy"); // <= 1%
lowStakeDepositFee = _lowStakeDepositFee;
highStakeDepositFee = _highStakeDepositFee;
}
function SETUNLOCKWITHDRAWFEE126(uint256 _unlockWithdrawFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING
require(_unlockWithdrawFee <= 1000, "Dont be too greedy"); // <= 10%
unlockWithdrawFee = _unlockWithdrawFee;
}
// To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade)
function UPGRADEVUSDCONTRACT293(address _vUSDContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING
vUSD = IERC20(_vUSDContract);
}
// To upgrade vETH contract (v1 is still experimental, we may need vETHv2 with rebase() function working soon - then governance will call this upgrade)
function UPGRADEVETHCONTRACT116(address _vETHContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING
vETH = IERC20(_vETHContract);
}
modifier UPDATEREWARD641(address account) { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN11();
lastUpdateTime = LASTTIMEREWARDAPPLICABLE544();
if (account != address(0)) {
rewards[account] = EARNED432(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function LASTTIMEREWARDAPPLICABLE544() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN896(block.timestamp, periodFinish);
}
function REWARDPERTOKEN11() public view returns (uint256) { //inject NONSTANDARD NAMING
if (TOTALSUPPLY2() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.ADD124(
LASTTIMEREWARDAPPLICABLE544()
.SUB912(lastUpdateTime)
.MUL612(rewardRate)
.MUL612(1e18)
.DIV645(TOTALSUPPLY2())
);
}
// vUSD balance
function EARNED432(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 calculatedEarned = BALANCEOF265(account)
.MUL612(REWARDPERTOKEN11().SUB912(userRewardPerTokenPaid[account]))
.DIV645(1e18)
.ADD124(rewards[account]);
uint256 poolBalance = vUSD.BALANCEOF265(address(this));
// some rare case the reward can be slightly bigger than real number, we need to check against how much we have left in pool
if (calculatedEarned > poolBalance) return poolBalance;
return calculatedEarned;
}
function STAKINGPOWER96(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return accumulatedStakingPower[account].ADD124(EARNED432(account));
}
function VETHBALANCE317(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return EARNED432(account).DIV645(vETH_REWARD_FRACTION_RATE);
}
function STAKE230(uint256 amount, address referrer) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING
require(amount >= 1 szabo, "Do not stake dust");
require(referrer != msg.sender, "You cannot refer yourself.");
uint256 actualStakeAmount = amount;
uint256 depositFee = 0;
if (minStakingAmount > 0) {
if (amount < minStakingAmount && lowStakeDepositFee < 10000) {
// if amount is less than minStakingAmount and lowStakeDepositFee is not disabled
// if governance does not allow low stake
if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount");
// otherwise depositFee will be calculated based on the rate
else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000);
} else if (amount > minStakingAmount && highStakeDepositFee > 0) {
// if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount)
depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000);
}
if (depositFee > 0) {
actualStakeAmount = amount.SUB912(depositFee);
}
}
super.TOKENSTAKE952(amount, actualStakeAmount);
lastStakeTimes[msg.sender] = block.timestamp;
emit STAKED939(msg.sender, amount, actualStakeAmount);
if (depositFee > 0) {
if (yfvInsuranceFund != address(0)) { // send fee to insurance
yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee);
emit REWARDPAID896(yfvInsuranceFund, depositFee);
} else { // or burn
yfv.BURN805(depositFee);
emit BURNED28(depositFee);
}
}
if (rewardReferral != address(0) && referrer != address(0)) {
IYFVReferral(rewardReferral).SETREFERRER414(msg.sender, referrer);
}
}
function STAKEONBEHALF204(address stakeFor, uint256 amount) public UPDATEREWARD641(stakeFor) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING
require(amount >= 1 szabo, "Do not stake dust");
require(whitelistedPools[msg.sender], "Sorry hackers, you should stay away from us (YFV community signed)");
uint256 actualStakeAmount = amount;
uint256 depositFee = 0;
if (minStakingAmount > 0) {
if (amount < minStakingAmount && lowStakeDepositFee < 10000) {
// if amount is less than minStakingAmount and lowStakeDepositFee is not disabled
// if governance does not allow low stake
if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount");
// otherwise depositFee will be calculated based on the rate
else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000);
} else if (amount > minStakingAmount && highStakeDepositFee > 0) {
// if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount)
depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000);
}
if (depositFee > 0) {
actualStakeAmount = amount.SUB912(depositFee);
}
}
super.TOKENSTAKEONBEHALF333(stakeFor, amount, actualStakeAmount);
lastStakeTimes[stakeFor] = block.timestamp;
emit STAKED939(stakeFor, amount, actualStakeAmount);
if (depositFee > 0) {
actualStakeAmount = amount.SUB912(depositFee);
if (yfvInsuranceFund != address(0)) { // send fee to insurance
yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee);
emit REWARDPAID896(yfvInsuranceFund, depositFee);
} else { // or burn
yfv.BURN805(depositFee);
emit BURNED28(depositFee);
}
}
}
function UNFROZENSTAKETIME568(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return lastStakeTimes[account] + unstakingFrozenTime;
}
function WITHDRAW21(uint256 amount) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING
require(amount > 0, "Cannot withdraw 0");
uint256 actualWithdrawAmount = amount;
if (block.timestamp < UNFROZENSTAKETIME568(msg.sender)) {
// if coin is still frozen and governance does not allow stakers to unstake before timer ends
if (unlockWithdrawFee == 0) revert("Coin is still frozen");
// otherwise withdrawFee will be calculated based on the rate
uint256 withdrawFee = amount.MUL612(unlockWithdrawFee).DIV645(10000);
actualWithdrawAmount = amount.SUB912(withdrawFee);
if (yfvInsuranceFund != address(0)) { // send fee to insurance
yfv.SAFETRANSFER450(yfvInsuranceFund, withdrawFee);
emit REWARDPAID896(yfvInsuranceFund, withdrawFee);
} else { // or burn
yfv.BURN805(withdrawFee);
emit BURNED28(withdrawFee);
}
}
super.TOKENWITHDRAW537(amount, actualWithdrawAmount);
emit WITHDRAWN649(msg.sender, amount, actualWithdrawAmount);
}
function EXIT848() external { //inject NONSTANDARD NAMING
WITHDRAW21(BALANCEOF265(msg.sender));
GETREWARD938();
}
function GETREWARD938() public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING
uint256 reward = rewards[msg.sender];
if (reward > 0) {
accumulatedStakingPower[msg.sender] = accumulatedStakingPower[msg.sender].ADD124(rewards[msg.sender]);
rewards[msg.sender] = 0;
vUSD.SAFETRANSFER450(msg.sender, reward);
vETH.SAFETRANSFER450(msg.sender, reward.DIV645(vETH_REWARD_FRACTION_RATE));
emit REWARDPAID896(msg.sender, reward);
}
}
modifier CHECKNEXTEPOCH825() { //inject NONSTANDARD NAMING
require(periodFinish > 0, "Pool has not started");
if (block.timestamp >= periodFinish) {
currentEpochReward = epochReward;
if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) {
currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward
}
if (currentEpochReward > 0) {
if (!vUSD.MINTERS951(address(this)) || !vETH.MINTERS951(address(this))) {
currentEpochReward = 0;
} else {
vUSD.MINT263(address(this), currentEpochReward);
vETH.MINT263(address(this), currentEpochReward.DIV645(vETH_REWARD_FRACTION_RATE));
totalAccumulatedReward = totalAccumulatedReward.ADD124(currentEpochReward);
}
currentEpoch++;
}
rewardRate = currentEpochReward.DIV645(duration178);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.ADD124(duration178);
emit REWARDADDED885(currentEpochReward);
}
_;
}
// Start the pool with reward amount for this epoch
function NOTIFYREWARDAMOUNT832(uint256 reward) external ONLYOWNER527 UPDATEREWARD641(address(0)) { //inject NONSTANDARD NAMING
require(periodFinish == 0, "Only can call once to start staking");
currentEpochReward = reward;
if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) {
currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward
}
lastUpdateTime = block.timestamp;
if (block.timestamp < starttime) { // epoch zero
periodFinish = starttime;
rewardRate = reward.DIV645(periodFinish.SUB912(block.timestamp));
} else { // 1st epoch
periodFinish = lastUpdateTime.ADD124(duration178);
rewardRate = reward.DIV645(duration178);
currentEpoch++;
}
vUSD.MINT263(address(this), reward);
vETH.MINT263(address(this), reward.DIV645(vETH_REWARD_FRACTION_RATE));
totalAccumulatedReward = totalAccumulatedReward.ADD124(reward);
emit REWARDADDED885(reward);
}
// This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools.
// This is in an effort to make someone whole, should they seriously mess up.
// There is no guarantee governance will vote to return these.
// It also allows for removal of airdropped tokens.
function GOVERNANCERECOVERUNSUPPORTED727(IERC20 _token, uint256 amount, address to) external { //inject NONSTANDARD NAMING
// only gov
require(msg.sender == OWNER858(), "!governance");
// cant take staked asset
require(_token != yfv, "yfv");
// cant take reward asset
require(_token != vUSD, "vUSD");
require(_token != vETH, "vETH");
// transfer to
_token.SAFETRANSFER450(to, amount);
}
} | inject NONSTANDARD NAMING | function GETREFERRER855(address farmer) external view returns (address); | 7,225,429 |
// File @rari-capital/solmate/src/tokens/[email protected]
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
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, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
// File contracts/IGenzee.sol
pragma solidity ^0.8.4;
interface IGenzee {
function transferFrom(address from, address to, uint256 tokenId) external;
function ownerOf(uint256 tokenId) external returns (address);
function setApprovalForAll(address _operator, bool _approved) external;
function isApprovedForAll(address _owner, address _operator) external returns (bool);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File contracts/Oddworx.sol
pragma solidity ^0.8.4;
error NotOwnerOfToken();
error InvalidInput();
error NoTokensToClaim();
error NftHoldRewardsNotActive();
error NotAdmin();
/// @title Oddworx
/// @author Mytchall / Alephao
/// @notice General functions to mint, burn, reward NFT holders incl staking
contract Oddworx is ERC20, Pausable {
IGenzee immutable public _genzeeContract;
bool public nftHoldRewardsActive = true;
uint256 public NFT_STAKING_WEEKLY_REWARD_AMOUNT = 20 * 10 ** 18; // Doesn't have to be public
uint256 constant public NFT_HOLDING_WEEKLY_REWARD_AMOUNT = 10 * 10 ** 18;
struct StakingData {
address ownerAddress; // 160 bits
uint96 timestamp; // 96 bits
}
mapping(address => bool) public adminAddresses;
mapping(uint256 => StakingData) public stakedNft;
mapping(uint256 => uint256) public latestUnstakedClaimTimestamp;
constructor(address _nftContractAddress) ERC20("Oddworx", "ODDX", 18) {
_mint(msg.sender, 1000000000 * 10 ** 18);
_genzeeContract = IGenzee(_nftContractAddress);
adminAddresses[msg.sender] = true;
}
/// @notice emitted when an item is purchased
/// @param user address of the user that purchased an item
/// @param itemSKU the SKU of the item purchased
/// @param price the amount paid for the item
event ItemPurchased(address indexed user, uint256 itemSKU, uint256 price);
/// @notice emitted when a user stakes a token
/// @param user address of the user that staked the Genzee
/// @param genzee the id of the Genzee staked
event StakedNft(address indexed user, uint256 indexed genzee);
/// @notice emitted when a user unstakes a token
/// @param user address of the user that unstaked the Genzee
/// @param genzee the id of the Genzee unstaked
/// @param amount the amount of ODDX claimed
event UnstakedNft(address indexed user, uint256 indexed genzee, uint256 amount);
/// @notice emitted when a user claim NFT rewards
/// @param user address of the user that claimed ODDX
/// @param genzee the id of the Genzee that generated the rewards
/// @param amount the amount of ODDX claimed
event UserClaimedNftRewards(address indexed user, uint256 indexed genzee, uint256 amount);
modifier onlyAdmin() {
if (adminAddresses[msg.sender] != true) revert NotAdmin();
_;
}
/*///////////////////////////////////////////////////////////////
General Functions
//////////////////////////////////////////////////////////////*/
function mint(address to, uint256 amount) public onlyAdmin {
_mint(to, amount);
}
function burn(address _from, uint256 amount) public onlyAdmin {
if (balanceOf[_from] < amount) revert InvalidInput();
_burn(_from, amount);
}
function toggleAdminContract(address _adminAddress) public onlyAdmin {
adminAddresses[_adminAddress] = !adminAddresses[_adminAddress];
}
function pause() public onlyAdmin {
_pause();
}
function unpause() public onlyAdmin {
_unpause();
}
/*///////////////////////////////////////////////////////////////
Shop features
//////////////////////////////////////////////////////////////*/
/// @notice Buy item in shop by burning Oddx.
/// @param itemSKU A unique ID used to identify shop products.
/// @param amount Amount of Oddx to burn.
function buyItem(uint itemSKU, uint amount) public whenNotPaused {
if (balanceOf[msg.sender] < amount) revert InvalidInput();
_burn(msg.sender, amount);
emit ItemPurchased(msg.sender, itemSKU, amount);
}
/*///////////////////////////////////////////////////////////////
NFT Staking Rewards
//////////////////////////////////////////////////////////////*/
/// @notice stake genzees in this contract.
/// The Genzee owners need to approve this contract for transfering
/// before calling this function.
/// @param genzeeIds list of genzee ids to stake.
function stakeNfts(uint256[] calldata genzeeIds) external whenNotPaused {
if (genzeeIds.length == 0) revert InvalidInput();
uint256 genzeeId;
for (uint256 i; i < genzeeIds.length; i++) {
genzeeId = genzeeIds[i];
// No need to check ownership since transferFrom already checks that
// and the caller of this function should be the Genzee owner
stakedNft[genzeeId] = StakingData(msg.sender, uint96(block.timestamp));
_genzeeContract.transferFrom(msg.sender, address(this), genzeeId);
emit StakedNft(msg.sender, genzeeId);
}
}
/// @notice unstake genzees back to they rightful owners and pay them what it's owed in ODDX.
/// @param genzeeIds list of genzee ids to unstake.
function unstakeNfts(uint256[] calldata genzeeIds) external whenNotPaused {
if (genzeeIds.length == 0) revert InvalidInput();
// total rewards amount to claim (all genzees)
uint256 totalRewards;
// loop variables
// rewards for current genzee in the loop below
uint256 rewards;
// current genzeeid in the loop below
uint256 genzeeId;
// staking information for the current genzee in the loop below
StakingData memory stake;
for (uint256 i; i < genzeeIds.length; i++) {
genzeeId = genzeeIds[i];
stake = stakedNft[genzeeId];
if (stake.ownerAddress != msg.sender && stake.ownerAddress != address(0)) {
revert NotOwnerOfToken();
}
rewards = _stakedRewardsForTimestamp(genzeeId);
totalRewards += rewards;
// Reset timestamp for unstaked rewards
latestUnstakedClaimTimestamp[genzeeId] = block.timestamp;
// No need to run safeTransferFrom because we're returning the NFT to
// an address that was holding it before
_genzeeContract.transferFrom(address(this), stake.ownerAddress, genzeeId);
delete stakedNft[genzeeId];
emit UnstakedNft(msg.sender, genzeeId, rewards);
}
if (totalRewards > 0) {
_mint(msg.sender, totalRewards);
}
}
/// @notice Claim Staked NFT rewards in ODDX. Also resets general holding
/// timestamp so users can't double-claim for holding/staking.
/// @param genzeeIds list of genzee ids to claim rewards for.
function claimStakedNftRewards(uint256[] calldata genzeeIds) external whenNotPaused {
if (genzeeIds.length == 0) revert InvalidInput();
// total rewards amount to claim (all genzees)
uint256 totalRewards;
// loop variables
// rewards for current genzee in the loop below
uint256 rewards;
// current genzeeid in the loop below
uint256 genzeeId;
// staking information for the current genzee in the loop below
StakingData memory stake;
for (uint256 i; i < genzeeIds.length; i++) {
genzeeId = genzeeIds[i];
stake = stakedNft[genzeeId];
if (stake.ownerAddress != msg.sender) revert NotOwnerOfToken();
rewards = _stakedRewardsForTimestamp(stake.timestamp);
totalRewards += rewards;
stakedNft[genzeeId].timestamp = uint96(block.timestamp);
emit UserClaimedNftRewards(msg.sender, genzeeId, rewards);
}
if (totalRewards == 0) revert NoTokensToClaim();
_mint(msg.sender, totalRewards);
}
/// @notice Calculate staking rewards owed per week.
/// @param genzeeId NFT id to check.
/// @return Returns amount of tokens available to claim
function calculateStakedNftRewards(uint256 genzeeId) external view returns (uint256) {
uint256 timestamp = stakedNft[genzeeId].timestamp;
return _stakedRewardsForTimestamp(timestamp);
}
function _stakedRewardsForTimestamp(uint256 timestamp) private view returns (uint256) {
return timestamp > 0
? NFT_STAKING_WEEKLY_REWARD_AMOUNT * ((block.timestamp - timestamp) / 1 weeks)
: 0;
}
/// @notice Updates amount users are rewarded weekly.
/// @param newAmount new amount to use, supply number in wei.
function updateNftStakedRewardAmount(uint256 newAmount) external onlyAdmin {
NFT_STAKING_WEEKLY_REWARD_AMOUNT = newAmount;
}
/*///////////////////////////////////////////////////////////////
NFT Holding Rewards
//////////////////////////////////////////////////////////////*/
/// @notice Claim rewards for NFT if we are the holder.
/// Rewards are attached to the NFT, so if it's transferred, new owner can claim tokens
/// But the intital rewards can't be reclaimed
/// @param genzeeIds list of genzee ids to stake.
function claimNftHoldRewards(uint256[] calldata genzeeIds) external whenNotPaused {
if (!nftHoldRewardsActive) revert NftHoldRewardsNotActive();
if (genzeeIds.length == 0) revert InvalidInput();
// total rewards amount to claim (all genzees)
uint256 totalRewards;
// loop variables
// rewards for current genzee in the loop below
uint256 rewards;
// current genzeeid in the loop below
uint256 genzeeId;
// last time owner claimed rewards for the genzee
uint256 latestClaimTimestamp;
for (uint256 i; i < genzeeIds.length; i++) {
genzeeId = genzeeIds[i];
if (_genzeeContract.ownerOf(genzeeId) != msg.sender) revert NotOwnerOfToken();
latestClaimTimestamp = latestUnstakedClaimTimestamp[genzeeId];
rewards = _unstakedRewardsForTimestamp(latestClaimTimestamp);
totalRewards += rewards;
// Set claim timestamp to now
latestUnstakedClaimTimestamp[genzeeId] = block.timestamp;
emit UserClaimedNftRewards(msg.sender, genzeeId, rewards);
}
if (totalRewards == 0) revert NoTokensToClaim();
_mint(msg.sender, totalRewards);
}
function calculateNftHoldReward(uint256 _nftIndex) external view returns (uint256) {
uint256 timestamp = latestUnstakedClaimTimestamp[_nftIndex];
return _unstakedRewardsForTimestamp(timestamp);
}
function _unstakedRewardsForTimestamp(uint256 timestamp) private view returns (uint256) {
return (timestamp > 0)
? NFT_HOLDING_WEEKLY_REWARD_AMOUNT * ((block.timestamp - timestamp) / 1 weeks)
: NFT_HOLDING_WEEKLY_REWARD_AMOUNT;
}
function toggleNftHoldRewards() external onlyAdmin {
nftHoldRewardsActive = !nftHoldRewardsActive;
}
} | Claim Staked NFT rewards in ODDX. Also resets general holding timestamp so users can't double-claim for holding/staking. genzeeIds list of genzee ids to claim rewards for. total rewards amount to claim (all genzees) loop variables rewards for current genzee in the loop below current genzeeid in the loop below staking information for the current genzee in the loop below | function claimStakedNftRewards(uint256[] calldata genzeeIds) external whenNotPaused {
if (genzeeIds.length == 0) revert InvalidInput();
uint256 totalRewards;
uint256 rewards;
uint256 genzeeId;
StakingData memory stake;
for (uint256 i; i < genzeeIds.length; i++) {
genzeeId = genzeeIds[i];
stake = stakedNft[genzeeId];
if (stake.ownerAddress != msg.sender) revert NotOwnerOfToken();
rewards = _stakedRewardsForTimestamp(stake.timestamp);
totalRewards += rewards;
stakedNft[genzeeId].timestamp = uint96(block.timestamp);
emit UserClaimedNftRewards(msg.sender, genzeeId, rewards);
}
if (totalRewards == 0) revert NoTokensToClaim();
_mint(msg.sender, totalRewards);
}
| 5,342,448 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.