file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
pragma solidity ^0.6.6;
// SPDX-License-Identifier: MIT
/*
* @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
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
/**
* @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
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
/**
* @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 override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
/**
* @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);
}
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
/***********************************************************************
Modified @openzeppelin/contracts/token/ERC1155/IERC1155.sol
Allow overriding of some methods and use of some variables
in inherited contract.
----------------------------------------------------------------------*/
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external payable;
/**
* @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 payable;
}
// SPDX-License-Identifier: MIT
/***********************************************************************
Modified @openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol
Allow overriding of some methods and use of some variables
in inherited contract.
----------------------------------------------------------------------*/
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
/***********************************************************************
Modified @openzeppelin/contracts/token/ERC1155/ERC1155.sol
Allow overriding of some methods and use of some variables
in inherited contract.
----------------------------------------------------------------------*/
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _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 internal _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view 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
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) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public payable virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public payable virtual override {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(amount, "ERC1155: burn amount exceeds balance");
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(amounts[i], "ERC1155: burn amount exceeds balance");
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d,
string memory _e
) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// SPDX-License-Identifier: MIT
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor() internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// SPDX-License-Identifier: MIT
contract ERC1155Residuals is ERC1155, Ownable, WhitelistAdminRole {
using SafeMath for uint256;
using Address for address;
mapping(uint256 => address) public beneficiary;
mapping(uint256 => uint256) public residualsFee;
mapping(uint256 => bool) public residualsRequired;
uint256 public MAX_RESIDUALS = 10000;
event TransferWithResiduals(
address indexed from,
address indexed to,
uint256 id,
uint256 amount,
uint256 value,
uint256 residuals
);
/*
Not required:
? event TransferBatchWithResiduals(
address indexed from,
address indexed to,
uint256[] ids,
uint256[] amounts,
uint256 value
);
*/
event SetBeneficiary(uint256 indexed id, address indexed beneficiary);
event SetResidualsFee(uint256 indexed id, uint256 residualsFee);
event SetResidualsRequired(uint256 indexed id, bool recidualsRequired);
constructor(string memory uri_) public ERC1155(uri_) {}
function removeWhitelistAdmin(address account) public virtual onlyOwner {
_removeWhitelistAdmin(account);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public payable virtual override {
super.safeTransferFrom(from, to, id, amount, data);
if (_msgSender() != from && residualsRequired[id] && beneficiary[id] != address(0)) {
require(msg.value > 0, "ERC1155: residuals payment is required for this NFT");
}
if (msg.value > 0) {
if (beneficiary[id] != address(0)) {
uint256 residualsFeeValue = msg.value.mul(residualsFee[id]).div(MAX_RESIDUALS);
payable(beneficiary[id]).transfer(residualsFeeValue);
payable(from).transfer(msg.value.sub(residualsFeeValue));
// Emit only if residuals applied
emit TransferWithResiduals(from, to, id, amount, msg.value, residualsFeeValue);
} else {
payable(from).transfer(msg.value);
}
}
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public payable virtual override {
super.safeBatchTransferFrom(from, to, ids, amounts, data);
if (_msgSender() != from) {
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
require(
!(residualsRequired[id] && beneficiary[id] != address(0)),
Strings.strConcat("ERC1155: residuals payment is required in batch for token ", Strings.uint2str(id))
);
}
}
if (msg.value > 0) {
payable(from).transfer(msg.value);
}
// not ruquired -> emit TransferBatchWithResiduals(from, to, ids, amounts, msg.value);
}
function safeTransferFromWithResiduals(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public payable virtual {
super.safeTransferFrom(from, to, id, amount, data);
if (beneficiary[id] != address(0)) {
payable(beneficiary[id]).transfer(msg.value);
// Emit only if residuals applied
emit TransferWithResiduals(from, to, id, amount, msg.value, msg.value);
} else {
payable(msg.sender).transfer(msg.value);
}
}
function setBeneficiary(uint256 _id, address _beneficiary) public onlyWhitelistAdmin {
beneficiary[_id] = _beneficiary;
emit SetBeneficiary(_id, _beneficiary);
}
function setResidualsFee(uint256 _id, uint256 _residualsFee) public onlyWhitelistAdmin {
require(_residualsFee <= MAX_RESIDUALS, "ERC1155: to high residuals fee");
residualsFee[_id] = _residualsFee;
emit SetResidualsFee(_id, _residualsFee);
}
function setResidualsRequired(uint256 _id, bool _residualsRequired) public onlyWhitelistAdmin {
residualsRequired[_id] = _residualsRequired;
emit SetResidualsRequired(_id, _residualsRequired);
}
}
// SPDX-License-Identifier: MIT
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor() internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// SPDX-License-Identifier: MIT
interface IOwnableDelegateProxy {}
// SPDX-License-Identifier: MIT
contract IProxyRegistry {
mapping(address => IOwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address,
* has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract ERC1155Tradable is ERC1155Residuals, MinterRole {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress,
string memory uri_
) public ERC1155Residuals(uri_) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function removeWhitelistAdmin(address account) public override onlyOwner {
_removeWhitelistAdmin(account);
}
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function uri(uint256 _id) public view override returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(_uri, Strings.uint2str(_id), ".json");
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin {
_setURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* @param _maxSupply max supply allowed
* @param _initialSupply Optional amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Optional data to pass if receiver is contract
* @return tokenId The newly created token ID
*/
function create(
uint256 _maxSupply,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data,
address _beneficiary,
uint256 _residualsFee,
bool _residualsRequired
) external onlyWhitelistAdmin returns (uint256 tokenId) {
require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply");
require(_residualsFee <= MAX_RESIDUALS, "ERC1155Tradable: to high residuals fee");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
beneficiary[_id] = _beneficiary;
residualsFee[_id] = _residualsFee;
residualsRequired[_id] = _residualsRequired;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public onlyMinter {
uint256 tokenId = _id;
require(tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached");
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
IProxyRegistry proxyRegistry = IProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
/**
* @dev Updates token max supply
* @param id_ uint256 ID of the token to update
* @param maxSupply_ uint256 max supply allowed
*/
function updateTokenMaxSupply(uint256 id_, uint256 maxSupply_) external onlyWhitelistAdmin {
require(_exists(id_), "ERC1155Tradable#updateTokenMaxSupply: NONEXISTENT_TOKEN");
require(tokenSupply[id_] <= maxSupply_, "already minted > new maxSupply");
tokenMaxSupply[id_] = maxSupply_;
}
}
// SPDX-License-Identifier: MIT
/**
* @title RareNft
* RareNft - Collect limited edition NFTs from Rare
*/
contract RareNft is ERC1155Tradable {
string public contractURI;
constructor(
string memory _name, //// "Rare Ltd."
string memory _symbol, //// "$RARE"
address _proxyRegistryAddress,
string memory _baseMetadataURI, //// "https://api.rares.com/rares/"
string memory _contractURI //// "https://api.rares.com/contract/rares-erc1155"
) public ERC1155Tradable(_name, _symbol, _proxyRegistryAddress, _baseMetadataURI) {
contractURI = _contractURI;
}
} | * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings./ Whitelist OpenSea proxy contract for easy trading. | function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) {
IProxyRegistry proxyRegistry = IProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
| 13,849,578 | [
1,
6618,
353,
31639,
1290,
1595,
358,
10734,
729,
1807,
3502,
1761,
69,
2889,
9484,
358,
4237,
16189,
17,
9156,
666,
899,
18,
19,
3497,
7523,
3502,
1761,
69,
2889,
6835,
364,
12779,
1284,
7459,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
353,
31639,
1290,
1595,
12,
2867,
389,
8443,
16,
1758,
389,
9497,
13,
1071,
1476,
3849,
1135,
261,
6430,
353,
5592,
13,
288,
203,
565,
467,
3886,
4243,
2889,
4243,
273,
467,
3886,
4243,
12,
5656,
4243,
1887,
1769,
203,
565,
309,
261,
2867,
12,
5656,
4243,
18,
20314,
606,
24899,
8443,
3719,
422,
389,
9497,
13,
288,
203,
1377,
327,
638,
31,
203,
565,
289,
203,
203,
565,
327,
4232,
39,
2499,
2539,
18,
291,
31639,
1290,
1595,
24899,
8443,
16,
389,
9497,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/5/0x04882644f193Fb2bE3d49b68eb6c2FCaAaE606E2/sources/AirdropToken_staking.sol | function to allow admin to claim *other* ERC20 tokens sent to this contract (by mistake) | function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
if (_tokenAddr == tokenAddress) {
if (_amount > getStakingAndAirdropAmount()) {
revert();
}
totalClaimedRewards = totalClaimedRewards.add(_amount);
}
Token(_tokenAddr).transfer(_to, _amount);
}
| 16,855,967 | [
1,
915,
358,
1699,
3981,
358,
7516,
1308,
4232,
39,
3462,
2430,
3271,
358,
333,
6835,
261,
1637,
27228,
911,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
2961,
654,
39,
3462,
5157,
12,
2867,
389,
2316,
3178,
16,
1758,
389,
869,
16,
2254,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
309,
261,
67,
2316,
3178,
422,
1147,
1887,
13,
288,
203,
5411,
309,
261,
67,
8949,
405,
21491,
6159,
1876,
37,
6909,
1764,
6275,
10756,
288,
203,
7734,
15226,
5621,
203,
5411,
289,
203,
5411,
2078,
9762,
329,
17631,
14727,
273,
2078,
9762,
329,
17631,
14727,
18,
1289,
24899,
8949,
1769,
203,
3639,
289,
203,
3639,
3155,
24899,
2316,
3178,
2934,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../rewards-farmer/FarmerFactory.sol";
import "../rewards-farmer/COMPFarmer.sol";
import "../libraries/RewardsLib.sol";
import "../libraries/StorageLib.sol";
import "../interfaces/IAsset.sol";
import "../interfaces/ICToken.sol";
contract CompoundAdapter is IAsset, FarmerFactory {
using SafeMath for uint256;
event ExchangeRate(uint256 exchangeRate);
function hold(uint256 amount)
external
override(IAsset)
returns (uint256)
{
ICToken cToken = ICToken(StorageLib.assetToken());
IERC20 underlyingToken = IERC20(StorageLib.underlyingToken());
address proxy;
// if user does not have a proxy, deploy proxy
if (RewardsLib.farmerProxyAddress(msg.sender) == address(0)) {
proxy = deployProxy(
address(cToken),
address(underlyingToken),
// COMP token address
0xc00e94Cb662C3520282E6f5717214004A7f26888
);
// set mapping of user address to proxy
RewardsLib.setFarmerProxy(msg.sender, proxy);
} else {
proxy = RewardsLib.farmerProxyAddress(msg.sender);
}
// transfer underlying to the user's COMPFarmer to mint cToken
require(underlyingToken.transfer(proxy, amount));
// mint the interest bearing token
uint256 _amount = COMPFarmer(proxy).mint();
return _amount;
}
function withdraw(uint256 amount)
external
override(IAsset)
returns (uint256)
{
// get rewards farmer proxy
address proxy = RewardsLib.farmerProxyAddress(msg.sender);
IERC20 underlyingToken = IERC20(StorageLib.underlyingToken());
// identify SaveToken's underlying balance
uint256 initialUnderlyingBalance = underlyingToken.balanceOf(address(this));
COMPFarmer(proxy).redeem(amount, msg.sender);
// identify SaveToken's updated underlying balance
uint256 updatedUnderlyingBalance = underlyingToken.balanceOf(address(this));
return updatedUnderlyingBalance.sub(initialUnderlyingBalance);
}
function withdrawReward()
external
override(IAsset)
returns (uint256)
{
// get rewards farmer proxy
address proxy = RewardsLib.farmerProxyAddress(msg.sender);
return COMPFarmer(proxy).withdrawReward(msg.sender);
}
function getRewardsBalance()
external
override(IAsset)
returns (uint256)
{
// get rewards farmer proxy
address proxy = RewardsLib.farmerProxyAddress(msg.sender);
return COMPFarmer(proxy).getTotalCOMPEarned();
}
function transfer(address recipient, uint256 amount)
external
override(IAsset)
returns (bool)
{
address senderProxy = RewardsLib.farmerProxyAddress(msg.sender);
address recipientProxy = RewardsLib.farmerProxyAddress(recipient);
// if recipient does not have a proxy, deploy a proxy
if (recipientProxy == address(0)) {
recipientProxy = _deployProxy(recipient);
}
// transfer interest bearing token to recipient
return COMPFarmer(senderProxy).transfer(recipientProxy, amount);
}
function transferFrom(address sender, address recipient, uint256 amount)
external
override(IAsset)
returns (bool)
{
address senderProxy = RewardsLib.farmerProxyAddress(sender);
address recipientProxy = RewardsLib.farmerProxyAddress(recipient);
// if recipient does not have a proxy, deploy a proxy
if (recipientProxy == address(0)) {
recipientProxy = _deployProxy(recipient);
}
// transfer interest bearing token to recipient
return COMPFarmer(senderProxy).transfer(recipientProxy, amount);
}
// calculate underlying needed to mint _amount of cToken and mint tokens
function getCostOfAsset(uint256 amount)
external
override(IAsset)
returns (uint256)
{
ICToken cToken = ICToken(StorageLib.assetToken());
// calculate amount of underlying asset needed to mint amount of cToken
uint256 exchangeRate = cToken.exchangeRateCurrent();
emit ExchangeRate(exchangeRate);
return amount.mul(exchangeRate).add(10**18 - 1).div(10**18);
}
function _deployProxy(address recipient) internal returns (address) {
address cToken = StorageLib.assetToken();
address underlyingToken = StorageLib.underlyingToken();
address recipientProxy = deployProxy(
cToken,
underlyingToken,
// COMP token address
0xc00e94Cb662C3520282E6f5717214004A7f26888
);
// set mapping of recipient address to proxy
RewardsLib.setFarmerProxy(recipient, recipientProxy);
return recipientProxy;
}
}
| mint the interest bearing token | uint256 _amount = COMPFarmer(proxy).mint();
| 5,477,027 | [
1,
81,
474,
326,
16513,
30261,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
389,
8949,
273,
13846,
42,
4610,
264,
12,
5656,
2934,
81,
474,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions". This adds two-phase
* ownership control to OpenZeppelin's Ownable class. In this model, the original owner
* designates a new owner but does not actually transfer ownership. The new owner then accepts
* ownership and completes the transfer.
*/
contract Ownable {
address public owner;
address public pendingOwner;
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;
pendingOwner = address(0);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @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));
pendingOwner = _newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* Utility library of inline functions on addresses
*/
// library AddressUtils {
// /**
// * Returns whether the target address is a contract
// * @dev This function will return false if invoked during the constructor of a contract,
// * as the code is not actually created until after the constructor finishes.
// * @param addr address to check
// * @return whether the target address is a contract
// */
// function isContract(address addr) internal view returns (bool) {
// uint256 size;
// // XXX Currently there is no better way to check if there is a contract in an address
// // than to check the size of the code at that address.
// // See https://ethereum.stackexchange.com/a/14016/36603
// // for more details about how this works.
// // TODO Check this again before the Serenity release, because all addresses will be
// // contracts then.
// // solium-disable-next-line security/no-inline-assembly
// assembly { size := extcodesize(addr) }
// return size > 0;
// }
// }
/**
* @title PermissionedTokenStorage
* @notice a PermissionedTokenStorage is constructed by setting Regulator, BalanceSheet, and AllowanceSheet locations.
* Once the storages are set, they cannot be changed.
*/
contract PermissionedTokenStorage is Ownable {
using SafeMath for uint256;
/**
Storage
*/
mapping (address => mapping (address => uint256)) public allowances;
mapping (address => uint256) public balances;
uint256 public totalSupply;
function addAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].add(_value);
}
function subAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].sub(_value);
}
function setAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = _value;
}
function addBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].add(_value);
}
function subBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].sub(_value);
}
function setBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = _value;
}
function addTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.add(_value);
}
function subTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.sub(_value);
}
function setTotalSupply(uint256 _value) public onlyOwner {
totalSupply = _value;
}
}
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Contract constructor.
* @param _implementation Address of the initial implementation.
*/
constructor(address _implementation) public {
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_implementation);
}
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) private {
require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/
contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant CONVERT_WT_SIG = bytes4(keccak256("convertWT(uint256)"));
bytes4 public constant BURN_SIG = bytes4(keccak256("burn(uint256)"));
bytes4 public constant CONVERT_CARBON_DOLLAR_SIG = bytes4(keccak256("convertCarbonDollar(address,uint256)"));
bytes4 public constant BURN_CARBON_DOLLAR_SIG = bytes4(keccak256("burnCarbonDollar(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
}
/**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/
contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogWhitelistedUser(address indexed who);
event LogBlacklistedUser(address indexed who);
event LogNonlistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "whitelisted" user.
* @param _who The address of the account that we are setting permissions for.
*/
function setWhitelistedUser(address _who) public onlyValidator {
_setWhitelistedUser(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Sets the necessary permissions for a "nonlisted" user. Nonlisted users can trade tokens,
* but cannot burn them (and therefore cannot convert them into fiat.)
* @param _who The address of the account that we are setting permissions for.
*/
function setNonlistedUser(address _who) public onlyValidator {
_setNonlistedUser(_who);
}
/** Returns whether or not a user is whitelisted.
* @param _who The address of the account in question.
* @return `true` if the user is whitelisted, `false` otherwise.
*/
function isWhitelistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BURN_SIG) && !hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (!hasUserPermission(_who, BURN_SIG) && hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is nonlisted.
* @param _who The address of the account in question.
* @return `true` if the user is nonlisted, `false` otherwise.
*/
function isNonlistedUser(address _who) public view returns (bool) {
return (!hasUserPermission(_who, BURN_SIG) && !hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return hasUserPermission(_who, MINT_SIG);
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
setUserPermission(_who, MINT_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setNonlistedUser(address _who) internal {
require(isPermission(BURN_SIG), "Burn method not supported by token");
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BURN_SIG);
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogNonlistedUser(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BURN_SIG), "Burn method not supported by token");
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BURN_SIG);
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _setWhitelistedUser(address _who) internal {
require(isPermission(BURN_SIG), "Burn method not supported by token");
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BURN_SIG);
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogWhitelistedUser(_who);
}
}
/**
* @title PermissionedTokenProxy
* @notice A proxy contract that serves the latest implementation of PermissionedToken.
*/
contract PermissionedTokenProxy is UpgradeabilityProxy, Ownable {
PermissionedTokenStorage public tokenStorage;
Regulator public regulator;
// Events
event ChangedRegulator(address indexed oldRegulator, address indexed newRegulator );
/**
* @dev create a new PermissionedToken as a proxy contract
* with a brand new data storage
**/
constructor(address _implementation, address _regulator)
UpgradeabilityProxy(_implementation) public {
regulator = Regulator(_regulator);
tokenStorage = new PermissionedTokenStorage();
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) public onlyOwner {
_upgradeTo(newImplementation);
}
/**
* @return The address of the implementation.
*/
function implementation() public view returns (address) {
return _implementation();
}
}
/**
* @title WhitelistedTokenRegulator
* @dev WhitelistedTokenRegulator is a type of Regulator that modifies its definitions of
* what constitutes a "whitelisted/nonlisted/blacklisted" user. A WhitelistedToken
* provides a user the additional ability to convert from a whtielisted stablecoin into the
* meta-token CUSD, or mint CUSD directly through a specific WT.
*
*/
contract WhitelistedTokenRegulator is Regulator {
function isMinter(address _who) public view returns (bool) {
return (super.isMinter(_who) && hasUserPermission(_who, MINT_CUSD_SIG));
}
// Getters
function isWhitelistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, CONVERT_WT_SIG) && super.isWhitelistedUser(_who));
}
function isBlacklistedUser(address _who) public view returns (bool) {
return (!hasUserPermission(_who, CONVERT_WT_SIG) && super.isBlacklistedUser(_who));
}
function isNonlistedUser(address _who) public view returns (bool) {
return (!hasUserPermission(_who, CONVERT_WT_SIG) && super.isNonlistedUser(_who));
}
/** Internal functions **/
// A WT minter should have option to either mint directly into CUSD via mintCUSD(), or
// mint the WT via an ordinary mint()
function _setMinter(address _who) internal {
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_CUSD_SIG);
super._setMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
super._removeMinter(_who);
}
// Setters
// A WT whitelisted user should gain ability to convert their WT into CUSD. They can also burn their WT, as a
// PermissionedToken whitelisted user can do
function _setWhitelistedUser(address _who) internal {
require(isPermission(CONVERT_WT_SIG), "Converting to CUSD not supported by token");
setUserPermission(_who, CONVERT_WT_SIG);
super._setWhitelistedUser(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(CONVERT_WT_SIG), "Converting to CUSD not supported by token");
removeUserPermission(_who, CONVERT_WT_SIG);
super._setBlacklistedUser(_who);
}
function _setNonlistedUser(address _who) internal {
require(isPermission(CONVERT_WT_SIG), "Converting to CUSD not supported by token");
removeUserPermission(_who, CONVERT_WT_SIG);
super._setNonlistedUser(_who);
}
}
/**
* @title WhitelistedTokenProxy
* @notice This contract IS a WhitelistedToken. All calls to the WhitelistedToken contract will
* be routed through this proxy, since this proxy contract is the owner of the
* storage contracts.
*/
contract WhitelistedTokenProxy is PermissionedTokenProxy {
address public cusdAddress;
constructor(address _implementation,
address _regulator,
address _cusd) public PermissionedTokenProxy(_implementation, _regulator) {
// base class override
regulator = WhitelistedTokenRegulator(_regulator);
cusdAddress = _cusd;
}
}
/**
*
* @dev WhitelistedTokenProxyFactory creates new WhitelistedTokenProxy contracts with new data storage sheets, properly configured
* with ownership, and the proxy logic implementations are based on a user-specified WhitelistedTokenProxy.
*
**/
contract WhitelistedTokenProxyFactory {
// Parameters
address[] public tokens;
// Events
event CreatedWhitelistedTokenProxy(address newToken, uint256 index);
/**
*
* @dev generate a new proxy address that users can cast to a PermissionedToken or PermissionedTokenProxy. The
* proxy has empty data storage contracts connected to it and it is set with an initial logic contract
* to which it will delegate functionality
* @param regulator the address of the initial regulator contract that regulates the proxy
* @param tokenImplementation the address of the initial PT token implementation
*
**/
function createToken(address tokenImplementation, address cusdAddress, address regulator) public {
address proxy = address(new WhitelistedTokenProxy(tokenImplementation, regulator, cusdAddress));
// The function caller should own the proxy contract
WhitelistedTokenProxy(proxy).transferOwnership(msg.sender);
tokens.push(proxy);
emit CreatedWhitelistedTokenProxy(proxy, getCount()-1);
}
// Return number of token proxy contracts created so far
function getCount() public view returns (uint256) {
return tokens.length;
}
// Return the i'th created token
function getToken(uint256 i) public view returns(address) {
require((i < tokens.length) && (i >= 0), "Invalid index");
return tokens[i];
}
} | * @title WhitelistedTokenProxy @notice This contract IS a WhitelistedToken. All calls to the WhitelistedToken contract will be routed through this proxy, since this proxy contract is the owner of the storage contracts./ | contract WhitelistedTokenProxy is PermissionedTokenProxy {
address public cusdAddress;
constructor(address _implementation,
address _regulator,
address _cusd) public PermissionedTokenProxy(_implementation, _regulator) {
regulator = WhitelistedTokenRegulator(_regulator);
cusdAddress = _cusd;
}
}
| 10,568,810 | [
1,
18927,
329,
1345,
3886,
225,
1220,
6835,
4437,
279,
3497,
7523,
329,
1345,
18,
4826,
4097,
358,
326,
3497,
7523,
329,
1345,
6835,
903,
506,
3237,
329,
3059,
333,
2889,
16,
3241,
333,
2889,
6835,
353,
326,
3410,
434,
326,
2502,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
3497,
7523,
329,
1345,
3886,
353,
8509,
329,
1345,
3886,
288,
203,
565,
1758,
1071,
27964,
72,
1887,
31,
203,
203,
203,
565,
3885,
12,
2867,
389,
30810,
16,
7010,
7734,
1758,
389,
1574,
11775,
16,
7010,
7734,
1758,
389,
71,
407,
72,
13,
1071,
8509,
329,
1345,
3886,
24899,
30810,
16,
389,
1574,
11775,
13,
288,
203,
3639,
960,
11775,
273,
3497,
7523,
329,
1345,
1617,
11775,
24899,
1574,
11775,
1769,
203,
203,
3639,
27964,
72,
1887,
273,
389,
71,
407,
72,
31,
203,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x15A2d6C2b4B9903C27f50Cb8B32160ab17F186E2/sources/contracts/GOOPsToken.sol | * @notice Set the token URI descriptor. @dev Only callable by the owner when not locked./ | function setDescriptor(IGOOPsDescriptor _descriptor) external override onlyOwner whenDescriptorNotLocked {
descriptor = _descriptor;
emit DescriptorUpdated(_descriptor);
}
| 16,431,654 | [
1,
694,
326,
1147,
3699,
4950,
18,
225,
5098,
4140,
635,
326,
3410,
1347,
486,
8586,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
3187,
12,
3047,
51,
3665,
87,
3187,
389,
12628,
13,
3903,
3849,
1338,
5541,
1347,
3187,
1248,
8966,
288,
203,
3639,
4950,
273,
389,
12628,
31,
203,
203,
3639,
3626,
12823,
7381,
24899,
12628,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
/**
* Interface for defining crowdsale pricing.
*/
contract PricingStrategy {
address public tier;
/** Interface declaration. */
function isPricingStrategy() public pure returns (bool) {
return true;
}
/** Self check if all references are correctly set.
*
* Checks that pricing strategy matches crowdsale parameters.
*/
function isSane() public pure returns (bool) {
return true;
}
/**
* @dev Pricing tells if this is a presale purchase or not.
@return False by default, true if a presale purchaser
*/
function isPresalePurchase() public pure returns (bool) {
return false;
}
/* How many weis one token costs */
function updateRate(uint oneTokenInCents) public;
/**
* When somebody tries to buy tokens for X eth, calculate how many tokens they get.
*
*
* @param value - What is the value of the transaction send in as wei
* @param tokensSold - how much tokens have been sold this far
* @param decimals - how many decimal units the token has
* @return Amount of tokens the investor receives
*/
function calculatePrice(uint value, uint tokensSold, uint decimals) public view returns (uint tokenAmount);
function oneTokenInWei(uint tokensSold, uint decimals) public view returns (uint);
}
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLibExt {
function times(uint a, uint b) public pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function divides(uint a, uint b) public pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function minus(uint a, uint b) public pure returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) public pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit)
external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2)
public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit)
external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit)
external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external view returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if (data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if (buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if (len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if (value <= 23) {
buf.append(uint8((major << 5) | value));
} else if (value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if (value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if (value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if (value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if (value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if ((address(OAR) == 0)||(getCodeSize(address(OAR)) == 0))
oraclize_setNetwork(networkID_auto);
if (address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97) && (b1 <= 102)) b1 -= 87;
else if ((b1 >= 65) && (b1 <= 70)) b1 -= 55;
else if ((b1 >= 48) && (b1 <= 57)) b1 -= 48;
if ((b2 >= 97) && (b2 <= 102)) b2 -= 87;
else if ((b2 >= 65) && (b2 <= 70)) b2 -= 55;
else if ((b2 >= 48) && (b2 <= 57)) b2 -= 48;
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if (h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if (h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if (subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i = 0; i < n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification,
// keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)) {
//unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
}
else
return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false) {
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset)
internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* Contract which exposes `ethInCents` which is the Ether price in USD cents.
* E.g. if 1 Ether is sold at 840.32 USD on the markets, the `ethInCents` will
* be `84032`.
*
* This price is supplied by Oraclize callback, which sets the value. Currently
* there is no proof provided for the callback, other then the value and the
* corresponding ID which was generated when this contract called Oraclize.
*
* If this contract runs out of Ether, the callback cycle will interrupt until
* the `update` function is called with a transaction which also replenishes the
* balance of the contract.
*/
contract ETHUSD is usingOraclize, Ownable {
uint256 public ethInCents;
event LogInfo(string description);
event LogPriceUpdate(uint256 price);
event LogUpdate(address indexed _owner, uint indexed _balance);
// Constructor
constructor (uint _ethInCents)
public payable {
ethInCents = _ethInCents;
emit LogUpdate(owner, address(this).balance);
// Replace the next line with your version:
oraclize_setNetwork(1);
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
update();
}
// Fallback function
function() public payable {
}
function __callback(bytes32 myid, string result, bytes proof) public {
require(msg.sender == oraclize_cbAddress());
ethInCents = parseInt(result, 2);
emit LogPriceUpdate(ethInCents);
update();
}
function getBalance() public view returns (uint _balance) {
return address(this).balance;
}
function update()
public payable
{
// Check if we have enough remaining funds
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
} else {
emit LogInfo("Oraclize query was sent, standing by for the answer..");
// Using XPath to to fetch the right element in the JSON response
oraclize_query(7200, "URL", "json(https://api.coinbase.com/v2/prices/ETH-USD/spot).data.amount");
}
}
function instantUpdate()
public payable
onlyOwner {
// Check if we have enough remaining funds
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogInfo("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
} else {
emit LogInfo("Oraclize query was sent, standing by for the answer..");
// Using XPath to to fetch the right element in the JSON response
oraclize_query("URL", "json(https://api.coinbase.com/v2/prices/ETH-USD/spot).data.amount");
}
}
function setEthInCents(uint _ethInCents)
public onlyOwner {
require(_ethInCents > 0);
ethInCents = _ethInCents;
}
function withdrawFunds(address _addr)
public
onlyOwner
{
if (msg.sender != owner) revert();
_addr.transfer(address(this).balance);
}
}
/**
* Fixed crowdsale pricing - everybody gets the same price.
*/
contract FlatPricingExt is PricingStrategy, Ownable {
using SafeMathLibExt for uint;
/* How many weis one token costs */
//uint public oneTokenInWei5;
uint public oneTokenInCents;
//uint public ethInCents;
ETHUSD public ethUsdObj;
// Crowdsale rate has been changed
event RateChanged(uint oneTokenInCents);
constructor(uint _oneTokenInCents, address _ethUSDAddress) public {
require(_oneTokenInCents > 0);
oneTokenInCents = _oneTokenInCents;
ethUsdObj = ETHUSD(_ethUSDAddress);
}
modifier onlyTier() {
if (msg.sender != address(tier))
revert();
_;
}
function setTier(address _tier) public onlyOwner {
assert(_tier != address(0));
assert(tier == address(0));
tier = _tier;
}
function setEthUSD(address _ethUSDAddress) public onlyOwner {
assert(_ethUSDAddress != address(0));
ethUsdObj = ETHUSD(_ethUSDAddress);
}
function updateRate(uint _oneTokenInCents) public onlyTier {
require(_oneTokenInCents > 0);
oneTokenInCents = _oneTokenInCents;
emit RateChanged(oneTokenInCents);
}
/**
* Calculate the current price for buy in amount.
*
*/
function calculatePrice(uint value, uint tokensSold, uint decimals) public view returns (uint) {
uint multiplier = 10 ** decimals;
uint oneTokenPriceInWei = oneTokenInWei(tokensSold, decimals);
return value.times(multiplier) / oneTokenPriceInWei;
}
function oneTokenInWei(uint tokensSold, uint decimals) public view returns (uint) {
uint multiplier = 10 ** decimals;
uint ethInCents = getEthInCents();
uint oneTokenInWei5 = oneTokenInCents.times(multiplier).divides(ethInCents);
uint oneTokenInWei1 = oneTokenInWei5.times(60).divides(100);
uint oneTokenInWei2 = oneTokenInWei5.times(80).divides(100);
uint oneTokenInWei3 = oneTokenInWei5.times(90).divides(100);
uint oneTokenInWei4 = oneTokenInWei5.times(95).divides(100);
if (tokensSold <= 25000000 * multiplier)
return oneTokenInWei1;
if (tokensSold > 25000000 * multiplier && tokensSold <= 80000000 * multiplier)
return oneTokenInWei2;
if (tokensSold > 80000000 * multiplier && tokensSold <= 120000000 * multiplier)
return oneTokenInWei3;
if (tokensSold > 120000000 * multiplier && tokensSold <= 140000000 * multiplier)
return oneTokenInWei4;
if (tokensSold > 140000000 * multiplier)
return oneTokenInWei5;
}
function getEthInCents() public view returns (uint) {
return ethUsdObj.ethInCents();
}
} | How many weis one token costs */* When somebody tries to buy tokens for X eth, calculate how many tokens they get. @param value - What is the value of the transaction send in as wei @param tokensSold - how much tokens have been sold this far @param decimals - how many decimal units the token has @return Amount of tokens the investor receives/* Safe unsigned safe math. Maintained here until merged to mainline zeppelin-solidity./ | library SafeMathLibExt {
function updateRate(uint oneTokenInCents) public;
function calculatePrice(uint value, uint tokensSold, uint decimals) public view returns (uint tokenAmount);
function oneTokenInWei(uint tokensSold, uint decimals) public view returns (uint);
}
function times(uint a, uint b) public pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function divides(uint a, uint b) public pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function minus(uint a, uint b) public pure returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) public pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
| 7,916,913 | [
1,
44,
543,
4906,
732,
291,
1245,
1147,
22793,
342,
5203,
2690,
3432,
9327,
358,
30143,
2430,
364,
1139,
13750,
16,
4604,
3661,
4906,
2430,
2898,
336,
18,
225,
460,
300,
18734,
353,
326,
460,
434,
326,
2492,
1366,
316,
487,
732,
77,
225,
2430,
55,
1673,
300,
3661,
9816,
2430,
1240,
2118,
272,
1673,
333,
10247,
225,
15105,
300,
3661,
4906,
6970,
4971,
326,
1147,
711,
327,
16811,
434,
2430,
326,
2198,
395,
280,
17024,
19,
14060,
9088,
4183,
4233,
18,
490,
1598,
8707,
2674,
3180,
5384,
358,
2774,
1369,
998,
881,
84,
292,
267,
17,
30205,
560,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
14060,
10477,
5664,
2482,
288,
203,
203,
565,
445,
1089,
4727,
12,
11890,
1245,
1345,
382,
39,
4877,
13,
1071,
31,
203,
203,
565,
445,
4604,
5147,
12,
11890,
460,
16,
2254,
2430,
55,
1673,
16,
2254,
15105,
13,
1071,
1476,
1135,
261,
11890,
1147,
6275,
1769,
203,
203,
565,
445,
1245,
1345,
382,
3218,
77,
12,
11890,
2430,
55,
1673,
16,
2254,
15105,
13,
1071,
1476,
1135,
261,
11890,
1769,
203,
97,
203,
203,
565,
445,
4124,
12,
11890,
279,
16,
2254,
324,
13,
1071,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
276,
273,
279,
380,
324,
31,
203,
3639,
1815,
12,
69,
422,
374,
747,
276,
342,
279,
422,
324,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
3739,
4369,
12,
11890,
279,
16,
2254,
324,
13,
1071,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
1815,
12,
70,
405,
374,
1769,
203,
3639,
2254,
276,
273,
279,
342,
324,
31,
203,
3639,
1815,
12,
69,
422,
324,
380,
276,
397,
279,
738,
324,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
12647,
12,
11890,
279,
16,
2254,
324,
13,
1071,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
1815,
12,
70,
1648,
279,
1769,
203,
3639,
327,
279,
300,
324,
31,
203,
565,
289,
203,
203,
565,
445,
8737,
12,
11890,
279,
16,
2254,
324,
13,
1071,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
276,
273,
279,
397,
324,
31,
203,
3639,
1815,
12,
71,
1545,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
// import './interfaces/IUniswapV2Callee.sol';
import "@openzeppelin/contracts/access/Ownable.sol";
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20, Ownable {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public override constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public override factory;
address public override token0;
address public override token1;
address ownerAddress;
address treasury;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public override price0CumulativeLast;
uint public override price1CumulativeLast;
uint public override kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
uint256 private releaseTime;
uint256 private lockTime = 2 days;
modifier lock() {
require(unlocked == 1, 'PolkaBridge AMM V1: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public override view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'PolkaBridge AMM V1: TRANSFER_FAILED');
}
constructor() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1, address _owner, address _treasury) external override {
require(msg.sender == factory, 'PolkaBridge AMM V1: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
ownerAddress = _owner;
treasury = _treasury;
}
function skim(address to) external override lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external override lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(int112(-1)) && balance1 <= uint112(int112(-1)), 'PolkaBridge AMM V1: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = address(0);//IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external override lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'PolkaBridge AMM V1: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external override lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'PolkaBridge AMM V1: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function burnETH(address to, address to1) external override lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'PolkaBridge AMM V1: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to1, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit BurnETH(msg.sender, amount0, amount1, to, to1);
}
// function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
// if (_i == 0) {
// return "0";
// }
// uint j = _i;
// uint len;
// while (j != 0) {
// len++;
// j /= 10;
// }
// bytes memory bstr = new bytes(len);
// uint k = len;
// while (_i != 0) {
// k = k-1;
// uint8 temp = (48 + uint8(_i - _i / 10 * 10));
// bytes1 b1 = bytes1(temp);
// bstr[k] = b1;
// _i /= 10;
// }
// return string(bstr);
// }
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to) external override lock {
// require(false, string(abi.encodePacked(uint2str(amount0Out), ' : ', uint2str(amount1Out))));
require(amount0Out > 0 || amount1Out > 0, 'PolkaBridge AMM V1: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'PolkaBridge AMM V1: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'PolkaBridge AMM V1: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'PolkaBridge AMM V1: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
// uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(2));
// uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(2));
// require(false, string(abi.encodePacked(uint2str(_reserve0), ' : ', uint2str(_reserve1), ' : ', uint2str(balance0), ' : ', uint2str(balance1), ' : ', uint2str(amount0In), ' : ', uint2str(amount1In))));
// require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'PolkaBridge AMM V1: K');
}
if(amount0In.mul(4).div(10000) > 0) {
require(treasury != address(0), 'Treasury address error');
_safeTransfer(token0, treasury, amount0In.mul(4).div(10000));
balance0 = balance0 - amount0In.mul(4).div(10000);
// _reserve0 = _reserve0 - uint112(amount0In.mul(4).div(10000));
}
if(amount1In.mul(4).div(10000) > 0) {
require(treasury != address(0), 'Treasury address error');
_safeTransfer(token1, treasury, amount1In.mul(4).div(10000));
balance1 = balance1 - amount1In.mul(4).div(10000);
// _reserve1 = _reserve1 - uint112(amount1In.mul(4).div(10000));
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
function setTreasuryAddress(address _treasury) external override {
require(msg.sender == ownerAddress, 'Only ownerAddress can set treasury');
{
require(block.timestamp - releaseTime >= lockTime, "current time is before release time");
treasury = _treasury;
releaseTime = block.timestamp;
emit TreasurySet(_treasury);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
function div(uint x, uint y) internal pure returns (uint) {
require (y > 0, 'SafeMath: denominator can not be zero');
return x/y;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import './IUniswapV2ERC20.sol';
interface IUniswapV2Pair is IUniswapV2ERC20 {
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event BurnETH(address indexed sender, uint amount0, uint amount1, address indexed to, address indexed to1);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
event TreasurySet(address _address);
function setTreasuryAddress(address _address) external;
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 burnETH(address to, address to1) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to) external;
function skim(address to) external;
function sync() external;
function initialize(address, address, address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
event TreasurySet(address _address);
function setTreasuryAddress(address _address) external;
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs() external view returns (uint);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public override constant name = 'PolkaBridge AMM V1';
string public override constant symbol = 'PBRAMM-V1';
uint8 public override constant decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
constructor() {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != uint(int(-1))) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp, 'PolkaBridge AMM V1: 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, 'PolkaBridge AMM V1: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// 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;
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);
}
} | this low-level function should be called from a contract which performs important safety checks | function mint(address to) external override lock returns (uint liquidity) {
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'PolkaBridge AMM V1: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
emit Mint(msg.sender, amount0, amount1);
}
| 14,643,854 | [
1,
2211,
4587,
17,
2815,
445,
1410,
506,
2566,
628,
279,
6835,
1492,
11199,
10802,
24179,
4271,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
12,
2867,
358,
13,
3903,
3849,
2176,
1135,
261,
11890,
4501,
372,
24237,
13,
288,
203,
3639,
2254,
11013,
20,
273,
467,
654,
39,
3462,
12,
2316,
20,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2254,
11013,
21,
273,
467,
654,
39,
3462,
12,
2316,
21,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2254,
3844,
20,
273,
11013,
20,
18,
1717,
24899,
455,
6527,
20,
1769,
203,
3639,
2254,
3844,
21,
273,
11013,
21,
18,
1717,
24899,
455,
6527,
21,
1769,
203,
203,
3639,
1426,
14036,
1398,
273,
389,
81,
474,
14667,
24899,
455,
6527,
20,
16,
389,
455,
6527,
21,
1769,
203,
3639,
309,
261,
67,
4963,
3088,
1283,
422,
374,
13,
288,
203,
5411,
4501,
372,
24237,
273,
2361,
18,
24492,
12,
8949,
20,
18,
16411,
12,
8949,
21,
13,
2934,
1717,
12,
6236,
18605,
67,
2053,
53,
3060,
4107,
1769,
203,
5411,
4501,
372,
24237,
273,
2361,
18,
1154,
12,
8949,
20,
18,
16411,
24899,
4963,
3088,
1283,
13,
342,
389,
455,
6527,
20,
16,
3844,
21,
18,
16411,
24899,
4963,
3088,
1283,
13,
342,
389,
455,
6527,
21,
1769,
203,
3639,
289,
203,
3639,
2583,
12,
549,
372,
24237,
405,
374,
16,
296,
5850,
7282,
13691,
432,
8206,
776,
21,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
67,
6236,
6404,
8284,
203,
3639,
389,
81,
474,
12,
869,
16,
4501,
372,
24237,
1769,
203,
203,
3639,
389,
2725,
12,
12296,
20,
16,
11013,
21,
16,
2
]
|
//Address: 0x10a5f6dbd1f9e56fe09df25b1163cd299d5d2413
//Contract name: EthernautsExplore
//Balance: 0.251 Ether
//Verification Date: 4/24/2018
//Transacion Count: 727
// CODE STARTS HERE
pragma solidity ^0.4.19;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Ethernauts
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function takeOwnership(uint256 _tokenId) public;
function implementsERC721() public pure returns (bool);
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// Extend this library for child contracts
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
if (a > b) {
return a;
} else {
return b;
}
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
if (a < b) {
return a;
} else {
return b;
}
}
}
/// @dev Base contract for all Ethernauts contracts holding global constants and functions.
contract EthernautsBase {
/*** CONSTANTS USED ACROSS CONTRACTS ***/
/// @dev Used by all contracts that interfaces with Ethernauts
/// The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @dev due solidity limitation we cannot return dynamic array from methods
/// so it creates incompability between functions across different contracts
uint8 public constant STATS_SIZE = 10;
uint8 public constant SHIP_SLOTS = 5;
// Possible state of any asset
enum AssetState { Available, UpForLease, Used }
// Possible state of any asset
// NotValid is to avoid 0 in places where category must be bigger than zero
enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember }
/// @dev Sector stats
enum ShipStats {Level, Attack, Defense, Speed, Range, Luck}
/// @notice Possible attributes for each asset
/// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
/// 00000010 - Producible - Product of a factory and/or factory contract.
/// 00000100 - Explorable- Product of exploration.
/// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
/// 00010000 - Permanent - Cannot be removed, always owned by a user.
/// 00100000 - Consumable - Destroyed after N exploration expeditions.
/// 01000000 - Tradable - Buyable and sellable on the market.
/// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 public ATTR_SEEDED = bytes2(2**0);
bytes2 public ATTR_PRODUCIBLE = bytes2(2**1);
bytes2 public ATTR_EXPLORABLE = bytes2(2**2);
bytes2 public ATTR_LEASABLE = bytes2(2**3);
bytes2 public ATTR_PERMANENT = bytes2(2**4);
bytes2 public ATTR_CONSUMABLE = bytes2(2**5);
bytes2 public ATTR_TRADABLE = bytes2(2**6);
bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7);
}
/// @notice This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern.
contract EthernautsAccessControl is EthernautsBase {
// This facet controls access control for Ethernauts.
// All roles have same responsibilities and rights, but there is slight differences between them:
//
// - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract.
// It is initially set to the address that created the smart contract.
//
// - The CTO: The CTO can change contract address, oracle address and plan for upgrades.
//
// - The COO: The COO can change contract address and add create assets.
//
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
/// @param newContract address pointing to new contract
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public ctoAddress;
address public cooAddress;
address public oracleAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyCTO() {
require(msg.sender == ctoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyOracle() {
require(msg.sender == oracleAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress ||
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 CTO. Only available to the current CTO or CEO.
/// @param _newCTO The address of the new CTO
function setCTO(address _newCTO) external {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress
);
require(_newCTO != address(0));
ctoAddress = _newCTO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as oracle.
/// @param _newOracle The address of oracle
function setOracle(address _newOracle) external {
require(msg.sender == ctoAddress);
require(_newOracle != address(0));
oracleAddress = _newOracle;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CTO account is compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Storage contract for Ethernauts Data. Common structs and constants.
/// @notice This is our main data storage, constants and data types, plus
// internal functions for managing the assets. It is isolated and only interface with
// a list of granted contracts defined by CTO
/// @author Ethernauts - Fernando Pauer
contract EthernautsStorage is EthernautsAccessControl {
function EthernautsStorage() public {
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
ctoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
cooAddress = msg.sender;
// the creator of the contract is the initial Oracle as well
oracleAddress = msg.sender;
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents.
function() external payable {
require(msg.sender == address(this));
}
/*** Mapping for Contracts with granted permission ***/
mapping (address => bool) public contractsGrantedAccess;
/// @dev grant access for a contract to interact with this contract.
/// @param _v2Address The contract address to grant access
function grantAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
contractsGrantedAccess[_v2Address] = true;
}
/// @dev remove access from a contract to interact with this contract.
/// @param _v2Address The contract address to be removed
function removeAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
delete contractsGrantedAccess[_v2Address];
}
/// @dev Only allow permitted contracts to interact with this contract
modifier onlyGrantedContracts() {
require(contractsGrantedAccess[msg.sender] == true);
_;
}
modifier validAsset(uint256 _tokenId) {
require(assets[_tokenId].ID > 0);
_;
}
/*** DATA TYPES ***/
/// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy
/// of this structure. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Asset {
// Asset ID is a identifier for look and feel in frontend
uint16 ID;
// Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers
uint8 category;
// The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring
uint8 state;
// Attributes
// byte pos - Definition
// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
// 00000010 - Producible - Product of a factory and/or factory contract.
// 00000100 - Explorable- Product of exploration.
// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
// 00010000 - Permanent - Cannot be removed, always owned by a user.
// 00100000 - Consumable - Destroyed after N exploration expeditions.
// 01000000 - Tradable - Buyable and sellable on the market.
// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 attributes;
// The timestamp from the block when this asset was created.
uint64 createdAt;
// The minimum timestamp after which this asset can engage in exploring activities again.
uint64 cooldownEndBlock;
// The Asset's stats can be upgraded or changed based on exploration conditions.
// It will be defined per child contract, but all stats have a range from 0 to 255
// Examples
// 0 = Ship Level
// 1 = Ship Attack
uint8[STATS_SIZE] stats;
// Set to the cooldown time that represents exploration duration for this asset.
// Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part.
uint256 cooldown;
// a reference to a super asset that manufactured the asset
uint256 builtBy;
}
/*** CONSTANTS ***/
// @dev Sanity check that allows us to ensure that we are pointing to the
// right storage contract in our EthernautsLogic(address _CStorageAddress) call.
bool public isEthernautsStorage = true;
/*** STORAGE ***/
/// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId
/// of each asset is actually an index into this array.
Asset[] public assets;
/// @dev A mapping from Asset UniqueIDs to the price of the token.
/// stored outside Asset Struct to save gas, because price can change frequently
mapping (uint256 => uint256) internal assetIndexToPrice;
/// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address.
mapping (uint256 => address) internal assetIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) internal ownershipTokenCount;
/// @dev A mapping from AssetUniqueIDs to an address that has been approved to call
/// transferFrom(). Each Asset can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) internal assetIndexToApproved;
/*** SETTERS ***/
/// @dev set new asset price
/// @param _tokenId asset UniqueId
/// @param _price asset price
function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts {
assetIndexToPrice[_tokenId] = _price;
}
/// @dev Mark transfer as approved
/// @param _tokenId asset UniqueId
/// @param _approved address approved
function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts {
assetIndexToApproved[_tokenId] = _approved;
}
/// @dev Assigns ownership of a specific Asset to an address.
/// @param _from current owner address
/// @param _to new owner address
/// @param _tokenId asset UniqueId
function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts {
// Since the number of assets is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
assetIndexToOwner[_tokenId] = _to;
// When creating new assets _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete assetIndexToApproved[_tokenId];
}
}
/// @dev A public method that creates a new asset and stores it. This
/// method does basic checking and should only be called from other contract when the
/// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts.
/// @param _creatorTokenID The asset who is father of this asset
/// @param _owner First owner of this asset
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
public onlyGrantedContracts
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
Asset memory asset = Asset({
ID: _ID,
category: _category,
builtBy: _creatorTokenID,
attributes: bytes2(_attributes),
stats: _stats,
state: _state,
createdAt: uint64(now),
cooldownEndBlock: _cooldownEndBlock,
cooldown: _cooldown
});
uint256 newAssetUniqueId = assets.push(asset) - 1;
// Check it reached 4 billion assets but let's just be 100% sure.
require(newAssetUniqueId == uint256(uint32(newAssetUniqueId)));
// store price
assetIndexToPrice[newAssetUniqueId] = _price;
// This will assign ownership
transfer(address(0), _owner, newAssetUniqueId);
return newAssetUniqueId;
}
/// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This
/// This method doesn't do any checking and should only be called when the
/// input data is known to be valid.
/// @param _tokenId The token ID
/// @param _creatorTokenID The asset that create that token
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
/// @param _cooldown asset cooldown index
function editAsset(
uint256 _tokenId,
uint256 _creatorTokenID,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint16 _cooldown
)
external validAsset(_tokenId) onlyCLevel
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
// store price
assetIndexToPrice[_tokenId] = _price;
Asset storage asset = assets[_tokenId];
asset.ID = _ID;
asset.category = _category;
asset.builtBy = _creatorTokenID;
asset.attributes = bytes2(_attributes);
asset.stats = _stats;
asset.state = _state;
asset.cooldown = _cooldown;
}
/// @dev Update only stats
/// @param _tokenId asset UniqueId
/// @param _stats asset state, see Asset Struct description
function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].stats = _stats;
}
/// @dev Update only asset state
/// @param _tokenId asset UniqueId
/// @param _state asset state, see Asset Struct description
function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].state = _state;
}
/// @dev Update Cooldown for a single asset
/// @param _tokenId asset UniqueId
/// @param _cooldown asset state, see Asset Struct description
function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock)
public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].cooldown = _cooldown;
assets[_tokenId].cooldownEndBlock = _cooldownEndBlock;
}
/*** GETTERS ***/
/// @notice Returns only stats data about a specific asset.
/// @dev it is necessary due solidity compiler limitations
/// when we have large qty of parameters it throws StackTooDeepException
/// @param _tokenId The UniqueId of the asset of interest.
function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) {
return assets[_tokenId].stats;
}
/// @dev return current price of an asset
/// @param _tokenId asset UniqueId
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return assetIndexToPrice[_tokenId];
}
/// @notice Check if asset has all attributes passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes == _attributes;
}
/// @notice Check if asset has any attribute passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes != 0x0;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _category see AssetCategory in EthernautsBase for possible states
function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) {
return assets[_tokenId].category == _category;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _state see enum AssetState in EthernautsBase for possible states
function isState(uint256 _tokenId, uint8 _state) public view returns (bool) {
return assets[_tokenId].state == _state;
}
/// @notice Returns owner of a given Asset(Token).
/// @dev Required for ERC-721 compliance.
/// @param _tokenId asset UniqueId
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
return assetIndexToOwner[_tokenId];
}
/// @dev Required for ERC-721 compliance
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _tokenId asset UniqueId
function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) {
return assetIndexToApproved[_tokenId];
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return assets.length;
}
/// @notice List all existing tokens. It can be filtered by attributes or assets with owner
/// @param _owner filter all assets by owner
function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns(
uint256[6][]
) {
uint256 totalAssets = assets.length;
if (totalAssets == 0) {
// Return an empty array
return new uint256[6][](0);
} else {
uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets);
uint256 resultIndex = 0;
bytes2 hasAttributes = bytes2(_withAttributes);
Asset memory asset;
for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) {
asset = assets[tokenId];
if (
(asset.state != uint8(AssetState.Used)) &&
(assetIndexToOwner[tokenId] == _owner || _owner == address(0)) &&
(asset.attributes & hasAttributes == hasAttributes)
) {
result[resultIndex][0] = tokenId;
result[resultIndex][1] = asset.ID;
result[resultIndex][2] = asset.category;
result[resultIndex][3] = uint256(asset.attributes);
result[resultIndex][4] = asset.cooldown;
result[resultIndex][5] = assetIndexToPrice[tokenId];
resultIndex++;
}
}
return result;
}
}
}
/// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant.
/// @notice This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
// It interfaces with EthernautsStorage provinding basic functions as create and list, also holds
// reference to logic contracts as Auction, Explore and so on
/// @author Ethernatus - Fernando Pauer
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
contract EthernautsOwnership is EthernautsAccessControl, ERC721 {
/// @dev Contract holding only data.
EthernautsStorage public ethernautsStorage;
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "Ethernauts";
string public constant symbol = "ETNT";
/********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/
/**********************************************************************/
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)'));
/*** EVENTS ***/
// Events as per ERC-721
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed approved, uint256 tokens);
/// @dev When a new asset is create it emits build event
/// @param owner The address of asset owner
/// @param tokenId Asset UniqueID
/// @param assetId ID that defines asset look and feel
/// @param price asset price
event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price);
function implementsERC721() public pure returns (bool) {
return true;
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721.
/// @param _interfaceID interface signature ID
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Checks if a given address is the current owner of a particular Asset.
/// @param _claimant the address we are validating against.
/// @param _tokenId asset UniqueId, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.ownerOf(_tokenId) == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _claimant the address we are confirming asset is approved for.
/// @param _tokenId asset UniqueId, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.approvedFor(_tokenId) == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Assets on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
ethernautsStorage.approve(_tokenId, _approved);
}
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ethernautsStorage.balanceOf(_owner);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfers a Asset to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Ethernauts specifically) or your Asset may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Asset to transfer.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets
// (except very briefly after it is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the storage contract to prevent accidental
// misuse. Auction or Upgrade contracts should only take ownership of assets
// through the allow + transferFrom flow.
require(_to != address(ethernautsStorage));
// You can only send your own asset.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
ethernautsStorage.transfer(msg.sender, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Grant another address the right to transfer a specific Asset via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Asset that can be transferred if this call succeeds.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transferred.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets (except for used assets).
require(_owns(_from, _tokenId));
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
ethernautsStorage.transfer(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transfered.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
_transferFrom(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function takeOwnership(uint256 _tokenId) public {
address _from = ethernautsStorage.ownerOf(_tokenId);
// Safety check to prevent against an unexpected 0x0 default.
require(_from != address(0));
_transferFrom(_from, msg.sender, _tokenId);
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return ethernautsStorage.totalSupply();
}
/// @notice Returns owner of a given Asset(Token).
/// @param _tokenId Token ID to get owner.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ethernautsStorage.ownerOf(_tokenId);
require(owner != address(0));
}
/// @dev Creates a new Asset with the given fields. ONly available for C Levels
/// @param _creatorTokenID The asset who is father of this asset
/// @param _price asset price
/// @param _assetID asset ID
/// @param _category see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
returns (uint256)
{
// owner must be sender
require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
0,
0
);
// emit the build event
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
/// @notice verify if token is in exploration time
/// @param _tokenId The Token ID that can be upgraded
function isExploring(uint256 _tokenId) public view returns (bool) {
uint256 cooldown;
uint64 cooldownEndBlock;
(,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId);
return (cooldown > now) || (cooldownEndBlock > uint64(block.number));
}
}
/// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts
/// @author Ethernatus - Fernando Pauer
contract EthernautsLogic is EthernautsOwnership {
// Set in case the logic contract is broken and an upgrade is required
address public newContractAddress;
/// @dev Constructor
function EthernautsLogic() public {
// the creator of the contract is the initial CEO, COO, CTO
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
// Starts paused.
paused = true;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCTO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @dev set a new reference to the NFT ownership contract
/// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage.
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused {
EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress);
require(candidateContract.isEthernautsStorage());
ethernautsStorage = candidateContract;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(ethernautsStorage != address(0));
require(newContractAddress == address(0));
// require this contract to have access to storage contract
require(ethernautsStorage.contractsGrantedAccess(address(this)) == true);
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the COO to capture the balance available to the contract.
function withdrawBalances(address _to) public onlyCLevel {
_to.transfer(this.balance);
}
/// return current contract balance
function getBalance() public view onlyCLevel returns (uint256) {
return this.balance;
}
}
/// @title The facet of the Ethernauts Explore contract that send a ship to explore the deep space.
/// @notice An owned ship can be send on an expedition. Exploration takes time
// and will always result in “success”. This means the ship can never be destroyed
// and always returns with a collection of loot. The degree of success is dependent
// on different factors as sector stats, gamma ray burst number and ship stats.
// While the ship is exploring it cannot be acted on in any way until the expedition completes.
// After the ship returns from an expedition the user is then rewarded with a number of objects (assets).
/// @author Ethernatus - Fernando Pauer
contract EthernautsExplore is EthernautsLogic {
/// @dev Delegate constructor to Nonfungible contract.
function EthernautsExplore() public
EthernautsLogic() {}
/*** EVENTS ***/
/// emit signal to anyone listening in the universe
event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time);
event Result(uint256 shipId, uint256 sectorID);
/*** CONSTANTS ***/
uint8 constant STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255
// @dev Sanity check that allows us to ensure that we are pointing to the
// right explore contract in our EthernautsCrewMember(address _CExploreAddress) call.
bool public isEthernautsExplore = true;
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
uint256 public TICK_TIME = 15; // time is always in minutes
// exploration fee
uint256 public percentageCut = 90;
int256 public SPEED_STAT_MAX = 30;
int256 public RANGE_STAT_MAX = 20;
int256 public MIN_TIME_EXPLORE = 60;
int256 public MAX_TIME_EXPLORE = 2160;
int256 public RANGE_SCALE = 2;
/// @dev Sector stats
enum SectorStats {Size, Threat, Difficulty, Slots}
/// @dev hold all ships in exploration
uint256[] explorers;
/// @dev A mapping from Ship token to the exploration index.
mapping (uint256 => uint256) public tokenIndexToExplore;
/// @dev A mapping from Asset UniqueIDs to the sector token id.
mapping (uint256 => uint256) public tokenIndexToSector;
/// @dev A mapping from exploration index to the crew token id.
mapping (uint256 => uint256) public exploreIndexToCrew;
/// @dev A mission counter for crew.
mapping (uint256 => uint16) public missions;
/// @dev A mapping from Owner Cut (wei) to the sector token id.
mapping (uint256 => uint256) public sectorToOwnerCut;
mapping (uint256 => uint256) public sectorToOracleFee;
/// @dev Get a list of ship exploring our universe
function getExplorerList() public view returns(
uint256[3][]
) {
uint256[3][] memory tokens = new uint256[3][](50);
uint256 index = 0;
for(uint256 i = 0; i < explorers.length && index < 50; i++) {
if (explorers[i] > 0) {
tokens[index][0] = explorers[i];
tokens[index][1] = tokenIndexToSector[explorers[i]];
tokens[index][2] = exploreIndexToCrew[i];
index++;
}
}
if (index == 0) {
// Return an empty array
return new uint256[3][](0);
} else {
return tokens;
}
}
/// @dev Get a list of ship exploring our universe
/// @param _shipTokenId The Token ID that represents a ship
function getIndexByShip(uint256 _shipTokenId) public view returns( uint256 ) {
for(uint256 i = 0; i < explorers.length; i++) {
if (explorers[i] == _shipTokenId) {
return i;
}
}
return 0;
}
function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel {
sectorToOwnerCut[_sectorId] = _ownerCut;
}
function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel {
sectorToOracleFee[_sectorId] = _oracleFee;
}
function setTickTime(uint256 _tickTime) external onlyCLevel {
TICK_TIME = _tickTime;
}
function setPercentageCut(uint256 _percentageCut) external onlyCLevel {
percentageCut = _percentageCut;
}
function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel {
missions[_tokenId] = _total;
}
/// @notice Explore a sector with a defined ship. Sectors contain a list of Objects that can be given to the players
/// when exploring. Each entry has a Drop Rate and are sorted by Sector ID and Drop rate.
/// The drop rate is a whole number between 0 and 1,000,000. 0 is 0% and 1,000,000 is 100%.
/// Every time a Sector is explored a random number between 0 and 1,000,000 is calculated for each available Object.
/// If the final result is lower than the Drop Rate of the Object, that Object will be rewarded to the player once
/// Exploration is complete. Only 1 to 5 Objects maximum can be dropped during one exploration.
/// (FUTURE VERSIONS) The final number will be affected by the user’s Ship Stats.
/// @param _shipTokenId The Token ID that represents a ship
/// @param _sectorTokenId The Token ID that represents a sector
/// @param _crewTokenId The Token ID that represents a crew
function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused {
// charge a fee for each exploration when the results are ready
require(msg.value >= sectorToOwnerCut[_sectorTokenId]);
// check if Asset is a ship or not
require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship)));
// check if _sectorTokenId is a sector or not
require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector)));
// Ensure the Ship is in available state, otherwise it cannot explore
require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available)));
// ship could not be in exploration
require(tokenIndexToExplore[_shipTokenId] == 0);
require(!isExploring(_shipTokenId));
// check if explorer is ship owner
require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId));
// check if owner sector is not empty
address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId);
// check if there is a crew and validating crew member
if (_crewTokenId > 0) {
// crew member should not be in exploration
require(!isExploring(_crewTokenId));
// check if Asset is a crew or not
require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember)));
// check if crew member is same owner
require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId));
}
/// store exploration data
tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId);
uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId);
// check if there is a crew and store data and change ship stats
if (_crewTokenId > 0) {
/// store crew exploration data
exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId;
missions[_crewTokenId]++;
//// grab crew stats and merge with ship
uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId);
_shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)];
_shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)];
if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT;
}
if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT;
}
}
/// set exploration time
uint256 time = uint256(_explorationTime(
_shipStats[uint256(ShipStats.Range)],
_shipStats[uint256(ShipStats.Speed)],
_sectorStats[uint256(SectorStats.Size)]
));
// exploration time in minutes converted to seconds
time *= 60;
uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number);
ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock);
// check if there is a crew store data and set crew exploration time
if (_crewTokenId > 0) {
/// store crew exploration time
ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock);
}
// to avoid mistakes and charge unnecessary extra fees
uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId];
/// emit signal to anyone listening in the universe
Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time);
// keeping oracle accounts with balance
oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]);
// paying sector owner
sectorOwner.transfer(payment);
// send excess back to explorer
msg.sender.transfer(feeExcess);
}
/// @notice Exploration is complete and at most 10 Objects will return during one exploration.
/// @param _shipTokenId The Token ID that represents a ship and can explore
/// @param _sectorTokenId The Token ID that represents a sector and can be explored
/// @param _IDs that represents a object returned from exploration
/// @param _attributes that represents attributes for each object returned from exploration
/// @param _stats that represents all stats for each object returned from exploration
function explorationResults(
uint256 _shipTokenId,
uint256 _sectorTokenId,
uint16[10] _IDs,
uint8[10] _attributes,
uint8[STATS_SIZE][10] _stats
)
external onlyOracle
{
uint256 cooldown;
uint64 cooldownEndBlock;
uint256 builtBy;
(,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId);
address owner = ethernautsStorage.ownerOf(_shipTokenId);
require(owner != address(0));
/// create objects returned from exploration
uint256 i = 0;
for (i = 0; i < 10 && _IDs[i] > 0; i++) {
_buildAsset(
_sectorTokenId,
owner,
0,
_IDs[i],
uint8(AssetCategory.Object),
uint8(_attributes[i]),
_stats[i],
cooldown,
cooldownEndBlock
);
}
// to guarantee at least 1 result per exploration
require(i > 0);
/// remove from explore list
explorers[tokenIndexToExplore[_shipTokenId]] = 0;
delete tokenIndexToExplore[_shipTokenId];
delete tokenIndexToSector[_shipTokenId];
/// emit signal to anyone listening in the universe
Result(_shipTokenId, _sectorTokenId);
}
/// @notice Cancel ship exploration in case it get stuck
/// @param _shipTokenId The Token ID that represents a ship and can explore
function cancelExplorationByShip(
uint256 _shipTokenId
)
external onlyCLevel
{
uint256 index = tokenIndexToExplore[_shipTokenId];
if (index > 0) {
/// remove from explore list
explorers[index] = 0;
if (exploreIndexToCrew[index] > 0) {
delete exploreIndexToCrew[index];
}
}
delete tokenIndexToExplore[_shipTokenId];
delete tokenIndexToSector[_shipTokenId];
}
/// @notice Cancel exploration in case it get stuck
/// @param _index The exploration position that represents a exploring ship
function cancelExplorationByIndex(
uint256 _index
)
external onlyCLevel
{
uint256 shipId = explorers[_index];
/// remove from exploration list
explorers[_index] = 0;
if (shipId > 0) {
delete tokenIndexToExplore[shipId];
delete tokenIndexToSector[shipId];
}
if (exploreIndexToCrew[_index] > 0) {
delete exploreIndexToCrew[_index];
}
}
/// @notice Add exploration in case contract needs to be add trxs from previous contract
/// @param _shipTokenId The Token ID that represents a ship
/// @param _sectorTokenId The Token ID that represents a sector
/// @param _crewTokenId The Token ID that represents a crew
function addExplorationByShip(
uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId
)
external onlyCLevel whenPaused
{
uint256 index = explorers.push(_shipTokenId) - 1;
/// store exploration data
tokenIndexToExplore[_shipTokenId] = index;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
// check if there is a crew and store data and change ship stats
if (_crewTokenId > 0) {
/// store crew exploration data
exploreIndexToCrew[index] = _crewTokenId;
missions[_crewTokenId]++;
}
ethernautsStorage.setAssetCooldown(_shipTokenId, now, uint64(block.number));
}
/// @dev Creates a new Asset with the given fields. ONly available for C Levels
/// @param _creatorTokenID The asset who is father of this asset
/// @param _price asset price
/// @param _assetID asset ID
/// @param _category see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
/// @param _cooldown see Asset Struct description
/// @param _cooldownEndBlock see Asset Struct description
function _buildAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
private returns (uint256)
{
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
_cooldown,
_cooldownEndBlock
);
// emit the build event
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
/// @notice Exploration Time: The time it takes to explore a Sector is dependent on the Sector Size
/// along with the Ship’s Range and Speed.
/// @param _shipRange ship range
/// @param _shipSpeed ship speed
/// @param _sectorSize sector size
function _explorationTime(
uint8 _shipRange,
uint8 _shipSpeed,
uint8 _sectorSize
) private view returns (int256) {
int256 minToExplore = 0;
minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1;
minToExplore = -72 * minToExplore;
minToExplore += MAX_TIME_EXPLORE;
uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX));
uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE);
int256 minExplore = (minToExplore - MIN_TIME_EXPLORE);
minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange));
minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10);
minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE);
return minToExplore;
}
/// @notice calcs a perc without float or double :(
function fraction(int256 _subject, int256 _numerator, int256 _denominator)
private pure returns (int256) {
int256 division = _subject * _numerator - _subject * _denominator;
int256 total = _subject * _denominator + division;
return total / _denominator;
}
/// @notice Any C-level can fix how many seconds per blocks are currently observed.
/// @param _secs The seconds per block
function setSecondsPerBlock(uint256 _secs) external onlyCLevel {
require(_secs > 0);
secondsPerBlock = _secs;
}
}
| @dev hold all ships in exploration @dev A mapping from Ship token to the exploration index. @dev A mapping from Asset UniqueIDs to the sector token id. @dev A mapping from exploration index to the crew token id. @dev A mission counter for crew. @dev A mapping from Owner Cut (wei) to the sector token id. @dev Get a list of ship exploring our universe Return an empty array | ) {
uint256[3][] memory tokens = new uint256[3][](50);
uint256 index = 0;
for(uint256 i = 0; i < explorers.length && index < 50; i++) {
if (explorers[i] > 0) {
tokens[index][0] = explorers[i];
tokens[index][1] = tokenIndexToSector[explorers[i]];
tokens[index][2] = exploreIndexToCrew[i];
index++;
}
}
if (index == 0) {
return new uint256[3][](0);
return tokens;
}
}
| 1,044,208 | [
1,
21056,
777,
699,
7146,
316,
22991,
22226,
225,
432,
2874,
628,
2638,
625,
1147,
358,
326,
22991,
22226,
770,
18,
225,
432,
2874,
628,
10494,
14584,
5103,
358,
326,
16323,
1147,
612,
18,
225,
432,
2874,
628,
22991,
22226,
770,
358,
326,
1519,
91,
1147,
612,
18,
225,
432,
29396,
3895,
364,
1519,
91,
18,
225,
432,
2874,
628,
16837,
385,
322,
261,
1814,
77,
13,
358,
326,
16323,
1147,
612,
18,
225,
968,
279,
666,
434,
24316,
22991,
6053,
3134,
29235,
2000,
392,
1008,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
262,
288,
203,
3639,
2254,
5034,
63,
23,
6362,
65,
3778,
2430,
273,
394,
2254,
5034,
63,
23,
6362,
29955,
3361,
1769,
203,
3639,
2254,
5034,
770,
273,
374,
31,
203,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
22991,
280,
414,
18,
2469,
597,
770,
411,
6437,
31,
277,
27245,
288,
203,
5411,
309,
261,
338,
412,
280,
414,
63,
77,
65,
405,
374,
13,
288,
203,
7734,
2430,
63,
1615,
6362,
20,
65,
273,
22991,
280,
414,
63,
77,
15533,
203,
7734,
2430,
63,
1615,
6362,
21,
65,
273,
1147,
1016,
774,
55,
1229,
63,
338,
412,
280,
414,
63,
77,
13563,
31,
203,
7734,
2430,
63,
1615,
6362,
22,
65,
273,
15233,
266,
1016,
774,
1996,
91,
63,
77,
15533,
203,
7734,
770,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
309,
261,
1615,
422,
374,
13,
288,
203,
5411,
327,
394,
2254,
5034,
63,
23,
6362,
29955,
20,
1769,
203,
5411,
327,
2430,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
// File: contracts\openzeppelin-solidity\contracts\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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;
}
}
// File: contracts\openzeppelin-solidity\contracts\lifecycle\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts\openzeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_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 Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_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 Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: contracts\AccountLockableToken.sol
contract AccountLockableToken is Ownable {
mapping(address => bool) public lockStates;
event LockAccount(address indexed lockAccount);
event UnlockAccount(address indexed unlockAccount);
/**
* @dev Throws if called by locked account
*/
modifier whenNotLocked() {
require(!lockStates[msg.sender]);
_;
}
/**
* @dev Lock target account
* @param _target Target account to lock
*/
function lockAccount(address _target) public onlyOwner returns (bool) {
require(_target != owner);
require(!lockStates[_target]);
lockStates[_target] = true;
emit LockAccount(_target);
return true;
}
/**
* @dev Unlock target account
* @param _target Target account to unlock
*/
function unlockAccount(address _target) public onlyOwner returns (bool) {
require(_target != owner);
require(lockStates[_target]);
lockStates[_target] = false;
emit UnlockAccount(_target);
return true;
}
}
// File: contracts\WithdrawableToken.sol
contract WithdrawableToken is BasicToken, Ownable {
using SafeMath for uint256;
bool public withdrawingFinished = false;
event Withdraw(address _from, address _to, uint256 _value);
event WithdrawFinished();
modifier canWithdraw() {
require(!withdrawingFinished);
_;
}
modifier hasWithdrawPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Withdraw the amount of tokens to onwer.
* @param _from address The address which owner want to withdraw tokens form.
* @param _value uint256 the amount of tokens to be transferred.
*/
function withdraw(address _from, uint256 _value) public
hasWithdrawPermission
canWithdraw
returns (bool)
{
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[owner] = balances[owner].add(_value);
emit Withdraw(_from, owner, _value);
return true;
}
/**
* @dev Withdraw the amount of tokens to another.
* @param _from address The address which owner want to withdraw tokens from.
* @param _to address The address which owner want to transfer to.
* @param _value uint256 the amount of tokens to be transferred.
*/
function withdrawFrom(address _from, address _to, uint256 _value) public
hasWithdrawPermission
canWithdraw
returns (bool)
{
require(_value <= balances[_from]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Withdraw(_from, _to, _value);
return true;
}
/**
* @dev Function to stop withdrawing new tokens.
* @return True if the operation was successful.
*/
function finishingWithdrawing() public
onlyOwner
canWithdraw
returns (bool)
{
withdrawingFinished = true;
emit WithdrawFinished();
return true;
}
}
// File: contracts\openzeppelin-solidity\contracts\math\Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a >= _b ? _a : _b;
}
function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a < _b ? _a : _b;
}
function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a >= _b ? _a : _b;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: contracts\MilestoneLockToken.sol
contract MilestoneLockToken is StandardToken, Ownable {
using SafeMath for uint256;
struct Policy {
uint256 kickOff;
uint256[] periods;
uint8[] percentages;
}
struct MilestoneLock {
uint8[] policies;
uint256[] standardBalances;
}
uint8 constant MAX_POLICY = 100;
uint256 constant MAX_PERCENTAGE = 100;
mapping(uint8 => Policy) internal policies;
mapping(address => MilestoneLock) internal milestoneLocks;
event SetPolicyKickOff(uint8 policy, uint256 kickOff);
event PolicyAdded(uint8 policy);
event PolicyRemoved(uint8 policy);
event PolicyAttributeAdded(uint8 policy, uint256 period, uint8 percentage);
event PolicyAttributeRemoved(uint8 policy, uint256 period);
event PolicyAttributeModified(uint8 policy, uint256 period, uint8 percentage);
/**
* @dev Transfer token for a specified address when enough available unlock balance.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public
returns (bool)
{
require(getAvailableBalance(msg.sender) >= _value);
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another when enough available unlock balance.
* @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(getAvailableBalance(_from) >= _value);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Distribute the amounts of tokens to from owner's balance with the milestone policy to a policy-free user.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _policy index of milestone policy to apply.
*/
function distributeWithPolicy(address _to, uint256 _value, uint8 _policy) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[owner]);
require(_policy < MAX_POLICY);
require(policies[_policy].periods.length > 0);
balances[owner] = balances[owner].sub(_value);
balances[_to] = balances[_to].add(_value);
uint8 policyIndex = _getAppliedPolicyIndex(_to, _policy);
if (policyIndex < MAX_POLICY) {
milestoneLocks[_to].standardBalances[policyIndex] =
milestoneLocks[_to].standardBalances[policyIndex].add(_value);
} else {
milestoneLocks[_to].policies.push(_policy);
milestoneLocks[_to].standardBalances.push(_value);
}
emit Transfer(owner, _to, _value);
return true;
}
/**
* @dev add milestone policy.
* @param _policy index of the milestone policy you want to add.
* @param _periods periods of the milestone you want to add.
* @param _percentages unlock percentages of the milestone you want to add.
*/
function addPolicy(uint8 _policy, uint256[] _periods, uint8[] _percentages) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
require(_periods.length > 0);
require(_percentages.length > 0);
require(_periods.length == _percentages.length);
require(policies[_policy].periods.length == 0);
policies[_policy].periods = _periods;
policies[_policy].percentages = _percentages;
emit PolicyAdded(_policy);
return true;
}
/**
* @dev remove milestone policy.
* @param _policy index of the milestone policy you want to remove.
*/
function removePolicy(uint8 _policy) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
delete policies[_policy];
emit PolicyRemoved(_policy);
return true;
}
/**
* @dev get milestone policy information.
* @param _policy index of milestone policy.
*/
function getPolicy(uint8 _policy) public
view
returns (uint256, uint256[], uint8[])
{
require(_policy < MAX_POLICY);
return (
policies[_policy].kickOff,
policies[_policy].periods,
policies[_policy].percentages
);
}
/**
* @dev set kickoff
* @param _policy index of milestone poicy.
* @param _time kickoff time of policy.
*/
function setKickOff(uint8 _policy, uint256 _time) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
require(policies[_policy].periods.length > 0);
policies[_policy].kickOff = _time;
return true;
}
/**
* @dev add attribute to milestone policy.
* @param _policy index of milestone policy.
* @param _period period of policy.
* @param _percentage percentage of unlocking when reaching policy.
*/
function addPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
revert();
return false;
}
}
policy.periods.push(_period);
policy.percentages.push(_percentage);
emit PolicyAttributeAdded(_policy, _period, _percentage);
return true;
}
/**
* @dev remove attribute from milestone policy.
* @param _policy index of milestone policy.
* @param _period period of target policy.
*/
function removePolicyAttribute(uint8 _policy, uint256 _period) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
_removeElementAt256(policy.periods, i);
_removeElementAt8(policy.percentages, i);
emit PolicyAttributeRemoved(_policy, _period);
return true;
}
}
revert();
return false;
}
/**
* @dev modify attribute from milestone policy.
* @param _policy index of milestone policy.
* @param _period period of target policy.
* @param _percentage percentage to modified.
*/
function modifyPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
policy.percentages[i] = _percentage;
emit PolicyAttributeModified(_policy, _period, _percentage);
return true;
}
}
revert();
return false;
}
/**
* @dev get policy's locked percentage of milestone policy from now.
* @param _policy index of milestone policy for calculate locked percentage.
*/
function getPolicyLockedPercentage(uint8 _policy) public view
returns (uint256)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
if (policy.periods.length == 0) {
return 0;
}
if (policy.kickOff == 0 ||
policy.kickOff > now) {
return MAX_PERCENTAGE;
}
uint256 unlockedPercentage = 0;
for (uint256 i = 0; i < policy.periods.length; ++i) {
if (policy.kickOff + policy.periods[i] <= now) {
unlockedPercentage =
unlockedPercentage.add(policy.percentages[i]);
}
}
if (unlockedPercentage > MAX_PERCENTAGE) {
return 0;
}
return MAX_PERCENTAGE - unlockedPercentage;
}
/**
* @dev change account's milestone policy.
* @param _to address for milestone policy applyed to.
* @param _prevPolicy index of original milestone policy.
* @param _newPolicy index of milestone policy to be changed.
*/
function modifyMilestoneTo(address _to, uint8 _prevPolicy, uint8 _newPolicy) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_prevPolicy < MAX_POLICY);
require(_newPolicy < MAX_POLICY);
require(_prevPolicy != _newPolicy);
require(policies[_prevPolicy].periods.length > 0);
require(policies[_newPolicy].periods.length > 0);
uint256 prevPolicyIndex = _getAppliedPolicyIndex(_to, _prevPolicy);
require(prevPolicyIndex < MAX_POLICY);
MilestoneLock storage milestoneLock = milestoneLocks[_to];
uint256 prevLockedBalance = milestoneLock.standardBalances[prevPolicyIndex];
uint256 newPolicyIndex = _getAppliedPolicyIndex(_to, _newPolicy);
if (newPolicyIndex < MAX_POLICY) {
milestoneLock.standardBalances[newPolicyIndex] =
milestoneLock.standardBalances[newPolicyIndex].add(prevLockedBalance);
_removeElementAt8(milestoneLock.policies, prevPolicyIndex);
_removeElementAt256(milestoneLock.standardBalances, prevPolicyIndex);
} else {
milestoneLock.policies.push(_newPolicy);
milestoneLock.standardBalances.push(prevLockedBalance);
}
return true;
}
/**
* @dev remove milestone policy from account.
* @param _from address for applied milestone policy removes from.
* @param _policy index of milestone policy remove.
*/
function removeMilestoneFrom(address _from, uint8 _policy) public
onlyOwner
returns (bool)
{
require(_from != address(0));
require(_policy < MAX_POLICY);
uint256 policyIndex = _getAppliedPolicyIndex(_from, _policy);
require(policyIndex < MAX_POLICY);
_removeElementAt8(milestoneLocks[_from].policies, policyIndex);
_removeElementAt256(milestoneLocks[_from].standardBalances, policyIndex);
return true;
}
/**
* @dev get accounts milestone policy state information.
* @param _account address for milestone policy applied.
*/
function getUserMilestone(address _account) public view
returns (uint8[], uint256[])
{
return (
milestoneLocks[_account].policies,
milestoneLocks[_account].standardBalances
);
}
/**
* @dev available unlock balance.
* @param _account address for available unlock balance.
*/
function getAvailableBalance(address _account) public view
returns (uint256)
{
return balances[_account].sub(getTotalLockedBalance(_account));
}
/**
* @dev calcuate locked balance of milestone policy from now.
* @param _account address for lock balance.
* @param _policy index of applied milestone policy.
*/
function getLockedBalance(address _account, uint8 _policy) public view
returns (uint256)
{
require(_policy < MAX_POLICY);
uint256 policyIndex = _getAppliedPolicyIndex(_account, _policy);
if (policyIndex >= MAX_POLICY) {
return 0;
}
MilestoneLock storage milestoneLock = milestoneLocks[_account];
uint256 lockedPercentage =
getPolicyLockedPercentage(milestoneLock.policies[policyIndex]);
return milestoneLock.standardBalances[policyIndex].div(MAX_PERCENTAGE).mul(lockedPercentage);
}
/**
* @dev calcuate locked balance of milestone policy from now.
* @param _account address for lock balance.
*/
function getTotalLockedBalance(address _account) public view
returns (uint256)
{
MilestoneLock storage milestoneLock = milestoneLocks[_account];
uint256 totalLockedBalance = 0;
for (uint256 i = 0; i < milestoneLock.policies.length; i++) {
totalLockedBalance = totalLockedBalance.add(
getLockedBalance(_account, milestoneLock.policies[i])
);
}
return totalLockedBalance;
}
/**
* @dev get milestone policy index applied to user.
* @param _to address The address which you want get to.
* @param _policy index of meilstone policy applied.
*/
function _getAppliedPolicyIndex(address _to, uint8 _policy) internal view
returns (uint8)
{
require(_policy < MAX_POLICY);
MilestoneLock storage milestoneLock = milestoneLocks[_to];
for (uint8 i = 0; i < milestoneLock.policies.length; i++) {
if (milestoneLock.policies[i] == _policy) {
return i;
}
}
return MAX_POLICY;
}
/**
* @dev utility for uint256 array
* @param _array target array
* @param _index array index to remove
*/
function _removeElementAt256(uint256[] storage _array, uint256 _index) internal
returns (bool)
{
if (_array.length <= _index) {
return false;
}
for (uint256 i = _index; i < _array.length - 1; i++) {
_array[i] = _array[i + 1];
}
delete _array[_array.length - 1];
_array.length--;
return true;
}
/**
* @dev utility for uint8 array
* @param _array target array
* @param _index array index to remove
*/
function _removeElementAt8(uint8[] storage _array, uint256 _index) internal
returns (bool)
{
if (_array.length <= _index) {
return false;
}
for (uint256 i = _index; i < _array.length - 1; i++) {
_array[i] = _array[i + 1];
}
delete _array[_array.length - 1];
_array.length--;
return true;
}
}
// File: contracts\dHena.sol
/**
* @title Hena token
*/
contract dHena is
Pausable,
MintableToken,
BurnableToken,
AccountLockableToken,
WithdrawableToken,
MilestoneLockToken
{
uint256 constant MAX_SUFFLY = 1000000000;
string public name;
string public symbol;
uint8 public decimals;
constructor() public {
name = "dHena";
symbol = "DHENA";
decimals = 18;
totalSupply_ = MAX_SUFFLY * 10 ** uint(decimals);
balances[owner] = totalSupply_;
emit Transfer(address(0), owner, totalSupply_);
}
/**
* @dev Transfer token for a specified address when if not paused and not locked account
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to anther when if not paused and not locked account
* @param _from address The address which you want to send tokens from.
* @param _to address The address which you want to transfer to.
* @param _value uint256 the amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) public
whenNotPaused
whenNotLocked
returns (bool)
{
require(!lockStates[_from]);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender when if not paused and not locked account
* @param _spender address which will spend the funds.
* @param _addedValue amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.increaseApproval(_spender, _addedValue);
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @param _spender address which will spend the funds.
* @param _subtractedValue amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
/**
* @dev Distribute the amount of tokens to owner's balance.
* @param _to The address to transfer to.
* @param _value The amount to be transffered.
*/
function distribute(address _to, uint256 _value) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[owner]);
balances[owner] = balances[owner].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(owner, _to, _value);
return true;
}
} | * @dev get policy's locked percentage of milestone policy from now. @param _policy index of milestone policy for calculate locked percentage./ | function getPolicyLockedPercentage(uint8 _policy) public view
returns (uint256)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
if (policy.periods.length == 0) {
return 0;
}
if (policy.kickOff == 0 ||
policy.kickOff > now) {
return MAX_PERCENTAGE;
}
uint256 unlockedPercentage = 0;
for (uint256 i = 0; i < policy.periods.length; ++i) {
if (policy.kickOff + policy.periods[i] <= now) {
unlockedPercentage =
unlockedPercentage.add(policy.percentages[i]);
}
}
if (unlockedPercentage > MAX_PERCENTAGE) {
return 0;
}
return MAX_PERCENTAGE - unlockedPercentage;
}
| 12,724,127 | [
1,
588,
3329,
1807,
8586,
11622,
434,
28664,
3329,
628,
2037,
18,
225,
389,
5086,
770,
434,
28664,
3329,
364,
4604,
8586,
11622,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1689,
1590,
8966,
16397,
12,
11890,
28,
389,
5086,
13,
1071,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2583,
24899,
5086,
411,
4552,
67,
26366,
1769,
203,
203,
3639,
7436,
2502,
3329,
273,
8923,
63,
67,
5086,
15533,
203,
203,
3639,
309,
261,
5086,
18,
20659,
18,
2469,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
540,
203,
3639,
309,
261,
5086,
18,
79,
1200,
7210,
422,
374,
747,
203,
5411,
3329,
18,
79,
1200,
7210,
405,
2037,
13,
288,
203,
5411,
327,
4552,
67,
3194,
19666,
2833,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
25966,
16397,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
3329,
18,
20659,
18,
2469,
31,
965,
77,
13,
288,
203,
5411,
309,
261,
5086,
18,
79,
1200,
7210,
397,
3329,
18,
20659,
63,
77,
65,
1648,
2037,
13,
288,
203,
7734,
25966,
16397,
273,
203,
10792,
25966,
16397,
18,
1289,
12,
5086,
18,
8849,
1023,
63,
77,
19226,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
309,
261,
318,
15091,
16397,
405,
4552,
67,
3194,
19666,
2833,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
327,
4552,
67,
3194,
19666,
2833,
300,
25966,
16397,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title 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) internal _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 internal _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 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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract Cryptocoin is ERC20, Claimable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
address public accICO;
constructor (
address _accICO,
uint256 _initialSupply)
public
{
require(_accICO != address(0));//audit recommendation
require(_initialSupply > 0);
name = "Cryptocoin";
symbol = "CCIN";
decimals = 18;
accICO = _accICO;
_totalSupply = _initialSupply * (10 ** uint256(decimals));
//Initial token distribution
_balances[_accICO] = totalSupply();
emit Transfer(address(0), _accICO, totalSupply());
}
function burn(uint256 amount) external {
require(amount <= _balances[msg.sender]);
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
emit Transfer(msg.sender, address(0), amount);
}
function() public { } //Audit recommendation
//Owner can claim any tokens that transfered
//to this contract address
function reclaimToken(ERC20 token) external onlyOwner {
require(address(token) != address(0));
uint256 balance = token.balanceOf(address(this));
token.transfer(owner, balance);
}
//***************************************************************
// ERC20 part of this contract based on best practices of
// https://github.com/OpenZeppelin/zeppelin-solidity
// Adapted and amended by IBERGroup, email:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e131f060d170413111c17121b3e171c1b0c50190c110b0e">[email protected]</a>;
// Telegram: https://t.me/msmobile
// https://t.me/alexamuek
// Code released under the MIT License(see git root).
////**************************************************************
} | audit recommendation
| require(_accICO != address(0)); | 7,877,875 | [
1,
17413,
10519,
18782,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1377,
2583,
24899,
8981,
2871,
51,
540,
480,
1758,
12,
20,
10019,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.16;
/**
* This contract specially developed for http://diceforslice.co
*
* What is it?
* This is a game that allows you to win an amount of ETH to your personal ethereum address.
* The possible winning depends on your stake and on amount of ETH in the bank.
*
* Wanna profit?
* Be a sponsor or referral - read more on http://diceforslice.co
*
* Win chances:
* 1 dice = 1/6
* 2 dice = 1/18
* 3 dice = 1/36
* 4 dice = 1/54
* 5 dice = 1/64
*/
/**
* @title Math
* @dev Math operations with safety checks that throw on error. Added: random and "float" divide for numbers
*/
library Math {
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;
}
function divf(int256 numerator, int256 denominator, uint256 precision) internal pure returns(int256) {
int256 _numerator = numerator * int256(10 ** (precision + 1));
int256 _quotient = ((_numerator / denominator) + 5) / 10;
return _quotient;
}
function percent(uint256 value, uint256 per) internal pure returns(uint256) {
return uint256((divf(int256(value), 100, 4) * int256(per)) / 10000);
}
}
/**
* @title Randomizer
* @dev Fuck me... >_<
*/
contract Randomizer {
function getRandomNumber(int256 min, int256 max) public returns(int256);
}
/**
* @title Ownable
* @dev Check contract ownable for some admin operations
*/
contract Ownable {
address public owner;
modifier onlyOwner() { require(msg.sender == owner); _; }
function Ownable() public {
owner = msg.sender;
}
function updateContractOwner(address newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @dev General contract
*/
contract DiceForSlice is Ownable {
// Contract events
event UserBet (address user, uint8 number1, uint8 number2, uint8 number3, uint8 number4, uint8 number5);
event DiceRoll (uint8 number1, uint8 number2, uint8 number3, uint8 number4, uint8 number5);
event Loser (address loser);
event WeHaveAWinner (address winner, uint256 amount);
event OMGItIsJackPot(address winner);
// Address storage for referral system
mapping(address => uint256) private bets;
// Randomizer contract
Randomizer private rand;
// Sponsor data
address private sponsor;
uint256 private sponsorDiff = 100000000000000000;
uint256 public sponsorValue = 0;
// Current balances of contract
// -bank - available reward value
// -stock - available value for restore bank in emergency
uint256 public bank = 0;
uint256 public stock = 0;
// Bet price
uint256 private betPrice = 500000000000000000;
// Current bet split rules (in percent)
uint8 private partBank = 55;
uint8 private partOwner = 20;
uint8 private partSponsor = 12;
uint8 private partStock = 10;
uint8 private partReferral = 3;
// Current rewards (in percent from bank)
uint8 private rewardOne = 10;
uint8 private rewardTwo = 20;
uint8 private rewardThree = 30;
uint8 private rewardFour = 50;
uint8 private jackPot = 100;
// Current number min max
uint8 private minNumber = 1;
uint8 private maxNumber = 6;
/**
* @dev Check is valid msg value
*/
modifier isValidBet(uint8 reward) {
require(msg.value == Math.percent(betPrice, reward));
_;
}
/**
* @dev Check bank not empty (empty is < betPrice eth)
*/
modifier bankNotEmpty() {
require(bank >= Math.percent(betPrice, rewardTwo));
require(address(this).balance >= bank);
_;
}
/**
* @dev Set randomizer address
*/
function setRandomizer(address _rand) external onlyOwner {
rand = Randomizer(_rand);
}
/**
* @dev Special method for fill contract bank
*/
function fillTheBank() external payable {
require(msg.value >= sponsorDiff);
if (msg.value >= sponsorValue + sponsorDiff) {
sponsorValue = msg.value;
sponsor = msg.sender;
}
bank = Math.add(bank, msg.value);
}
/**
* @dev Restore value from stock
*/
function appendStock(uint256 amount) external onlyOwner {
require(amount > 0);
require(stock >= amount);
bank = Math.add(bank, amount);
stock = Math.sub(stock, amount);
}
/**
* @dev Get full contract balance
*/
function getBalance() public view returns(uint256) {
return address(this).balance;
}
/**
* @dev Get random number
*/
function getRN() internal returns(uint8) {
return uint8(rand.getRandomNumber(minNumber, maxNumber + minNumber));
}
/**
* @dev Check is valid number
*/
function isValidNumber(uint8 number) private view returns(bool) {
return number >= minNumber && number <= maxNumber;
}
/**
* @dev Split user bet in some pieces:
* - 55% go to bank
* - 20% go to contract developer :)
* - 12% go to sponsor
* - 10% go to stock for future restores
* - 3% go to referral (if exists, if not - go into stock)
*/
function splitTheBet(address referral) private {
uint256 _partBank = Math.percent(msg.value, partBank);
uint256 _partOwner = Math.percent(msg.value, partOwner);
uint256 _partStock = Math.percent(msg.value, partStock);
uint256 _partSponsor = Math.percent(msg.value, partSponsor);
uint256 _partReferral = Math.percent(msg.value, partReferral);
bank = Math.add(bank, _partBank);
stock = Math.add(stock, _partStock);
owner.transfer(_partOwner);
sponsor.transfer(_partSponsor);
if (referral != address(0) && referral != msg.sender && bets[referral] > 0) {
referral.transfer(_partReferral);
} else {
stock = Math.add(stock, _partReferral);
}
}
/**
* @dev Check the winner
*/
function isWinner(uint8 required, uint8[5] numbers, uint8[5] randoms) private pure returns(bool) {
uint8 count = 0;
for (uint8 i = 0; i < numbers.length; i++) {
if (numbers[i] == 0) continue;
for (uint8 j = 0; j < randoms.length; j++) {
if (randoms[j] == 0) continue;
if (randoms[j] == numbers[i]) {
count++;
delete randoms[j];
break;
}
}
}
return count == required;
}
/**
* @dev Reward the winner
*/
function rewardTheWinner(uint8 reward) private {
uint256 rewardValue = Math.percent(bank, reward);
require(rewardValue <= getBalance());
require(rewardValue <= bank);
bank = Math.sub(bank, rewardValue);
msg.sender.transfer(rewardValue);
emit WeHaveAWinner(msg.sender, rewardValue);
}
/**
* @dev Roll the dice for numbers
*/
function rollOne(address referral, uint8 number)
external payable isValidBet(rewardOne) bankNotEmpty {
require(isValidNumber(number));
bets[msg.sender]++;
splitTheBet(referral);
uint8[5] memory numbers = [number, 0, 0, 0, 0];
uint8[5] memory randoms = [getRN(), 0, 0, 0, 0];
emit UserBet(msg.sender, number, 0, 0, 0, 0);
emit DiceRoll(randoms[0], 0, 0, 0, 0);
if (isWinner(1, numbers, randoms)) {
rewardTheWinner(rewardOne);
} else {
emit Loser(msg.sender);
}
}
function rollTwo(address referral, uint8 number1, uint8 number2)
external payable isValidBet(rewardTwo) bankNotEmpty {
require(isValidNumber(number1) && isValidNumber(number2));
bets[msg.sender]++;
splitTheBet(referral);
uint8[5] memory numbers = [number1, number2, 0, 0, 0];
uint8[5] memory randoms = [getRN(), getRN(), 0, 0, 0];
emit UserBet(msg.sender, number1, number2, 0, 0, 0);
emit DiceRoll(randoms[0], randoms[1], 0, 0, 0);
if (isWinner(2, numbers, randoms)) {
rewardTheWinner(rewardTwo);
} else {
emit Loser(msg.sender);
}
}
function rollThree(address referral, uint8 number1, uint8 number2, uint8 number3)
external payable isValidBet(rewardThree) bankNotEmpty {
require(isValidNumber(number1) && isValidNumber(number2) && isValidNumber(number3));
bets[msg.sender]++;
splitTheBet(referral);
uint8[5] memory numbers = [number1, number2, number3, 0, 0];
uint8[5] memory randoms = [getRN(), getRN(), getRN(), 0, 0];
emit UserBet(msg.sender, number1, number2, number3, 0, 0);
emit DiceRoll(randoms[0], randoms[1], randoms[2], 0, 0);
if (isWinner(3, numbers, randoms)) {
rewardTheWinner(rewardThree);
} else {
emit Loser(msg.sender);
}
}
function rollFour(address referral, uint8 number1, uint8 number2, uint8 number3, uint8 number4)
external payable isValidBet(rewardFour) bankNotEmpty {
require(isValidNumber(number1) && isValidNumber(number2) && isValidNumber(number3) && isValidNumber(number4));
bets[msg.sender]++;
splitTheBet(referral);
uint8[5] memory numbers = [number1, number2, number3, number4, 0];
uint8[5] memory randoms = [getRN(), getRN(), getRN(), getRN(), 0];
emit UserBet(msg.sender, number1, number2, number3, number4, 0);
emit DiceRoll(randoms[0], randoms[1], randoms[2], randoms[3], 0);
if (isWinner(4, numbers, randoms)) {
rewardTheWinner(rewardFour);
} else {
emit Loser(msg.sender);
}
}
function rollFive(address referral, uint8 number1, uint8 number2, uint8 number3, uint8 number4, uint8 number5)
external payable isValidBet(jackPot) bankNotEmpty {
require(isValidNumber(number1) && isValidNumber(number2) && isValidNumber(number3) && isValidNumber(number4) && isValidNumber(number5));
bets[msg.sender]++;
splitTheBet(referral);
uint8[5] memory numbers = [number1, number2, number3, number4, number5];
uint8[5] memory randoms = [getRN(), getRN(), getRN(), getRN(), getRN()];
emit UserBet(msg.sender, number1, number2, number3, number4, number5);
emit DiceRoll(randoms[0], randoms[1], randoms[2], randoms[3], randoms[4]);
if (isWinner(5, numbers, randoms)) {
rewardTheWinner(jackPot);
emit OMGItIsJackPot(msg.sender);
} else {
emit Loser(msg.sender);
}
}
} | * @dev Special method for fill contract bank/ | function fillTheBank() external payable {
require(msg.value >= sponsorDiff);
if (msg.value >= sponsorValue + sponsorDiff) {
sponsorValue = msg.value;
sponsor = msg.sender;
}
bank = Math.add(bank, msg.value);
}
| 11,695,593 | [
1,
12193,
707,
364,
3636,
6835,
11218,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3636,
1986,
16040,
1435,
3903,
8843,
429,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
272,
500,
2467,
5938,
1769,
203,
3639,
309,
261,
3576,
18,
1132,
1545,
272,
500,
2467,
620,
397,
272,
500,
2467,
5938,
13,
288,
203,
5411,
272,
500,
2467,
620,
273,
1234,
18,
1132,
31,
203,
5411,
272,
500,
2467,
1377,
273,
1234,
18,
15330,
31,
203,
3639,
289,
203,
3639,
11218,
273,
2361,
18,
1289,
12,
10546,
16,
1234,
18,
1132,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.15;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract tokenSPERT {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply = 0;
function tokenSPERT (string _name, string _symbol, uint8 _decimals){
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
}
contract Presale is owned, tokenSPERT {
string name = 'Pre-sale Eristica Token';
string symbol = 'SPERT';
uint8 decimals = 18;
function Presale ()
tokenSPERT (name, symbol, decimals){}
event Transfer(address _from, address _to, uint256 amount);
event Burned(address _from, uint256 amount);
function mintToken(address investor, uint256 mintedAmount) public onlyOwner {
balanceOf[investor] += mintedAmount;
totalSupply += mintedAmount;
Transfer(this, investor, mintedAmount);
}
function burnTokens(address _owner) public
onlyOwner
{
uint tokens = balanceOf[_owner];
if(balanceOf[_owner] == 0) throw;
balanceOf[_owner] = 0;
totalSupply -= tokens;
Burned(_owner, tokens);
}
}
library SafeMath {
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
uint public totalSupply = 0;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
function balanceOf(address _owner) constant returns (uint);
function transfer(address _to, uint _value) returns (bool);
function transferFrom(address _from, address _to, uint _value) returns (bool);
function approve(address _spender, uint _value) returns (bool);
function allowance(address _owner, address _spender) constant returns (uint);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
} // Functions of ERC20 standard
contract EristicaICO {
using SafeMath for uint;
uint public constant Tokens_For_Sale = 482500000*1e18; // Tokens for Sale (HardCap)
uint public Rate_Eth = 458; // Rate USD per ETH
uint public Token_Price = 50 * Rate_Eth; // ERT per ETH
uint public Sold = 0; //Sold tokens
event LogStartICO();
event LogPauseICO();
event LogFinishICO(address bountyFund, address advisorsFund, address teamFund, address challengeFund);
event LogBuyForInvestor(address investor, uint ertValue, string txHash);
event LogReplaceToken(address investor, uint ertValue);
ERT public ert = new ERT(this);
Presale public presale;
address public Company;
address public BountyFund;
address public AdvisorsFund;
address public TeamFund;
address public ChallengeFund;
address public Manager; // Manager controls contract
address public Controller_Address1; // First address that is used to buy tokens for other cryptos
address public Controller_Address2; // Second address that is used to buy tokens for other cryptos
address public Controller_Address3; // Third address that is used to buy tokens for other cryptos
modifier managerOnly { require(msg.sender == Manager); _; }
modifier controllersOnly { require((msg.sender == Controller_Address1) || (msg.sender == Controller_Address2) || (msg.sender == Controller_Address3)); _; }
uint bountyPart = 150; // 1.5% of TotalSupply for BountyFund
uint advisorsPart = 389; //3,89% of TotalSupply for AdvisorsFund
uint teamPart = 1000; //10% of TotalSupply for TeamFund
uint challengePart = 1000; //10% of TotalSupply for ChallengeFund
uint icoAndPOfPart = 7461; // 74,61% of TotalSupply for PublicICO and PrivateOffer
enum StatusICO { Created, Started, Paused, Finished }
StatusICO statusICO = StatusICO.Created;
function EristicaICO(address _presale, address _Company, address _BountyFund, address _AdvisorsFund, address _TeamFund, address _ChallengeFund, address _Manager, address _Controller_Address1, address _Controller_Address2, address _Controller_Address3){
presale = Presale(_presale);
Company = _Company;
BountyFund = _BountyFund;
AdvisorsFund = _AdvisorsFund;
TeamFund = _TeamFund;
ChallengeFund = _ChallengeFund;
Manager = _Manager;
Controller_Address1 = _Controller_Address1;
Controller_Address2 = _Controller_Address2;
Controller_Address3 = _Controller_Address3;
}
// function for changing rate of ETH and price of token
function setRate(uint _RateEth) external managerOnly {
Rate_Eth = _RateEth;
Token_Price = 50*Rate_Eth;
}
//ICO status functions
function startIco() external managerOnly {
require(statusICO == StatusICO.Created || statusICO == StatusICO.Paused);
LogStartICO();
statusICO = StatusICO.Started;
}
function pauseIco() external managerOnly {
require(statusICO == StatusICO.Started);
statusICO = StatusICO.Paused;
LogPauseICO();
}
function finishIco() external managerOnly { // Funds for minting of tokens
require(statusICO == StatusICO.Started);
uint alreadyMinted = ert.totalSupply(); //=PublicICO+PrivateOffer
uint totalAmount = alreadyMinted * 10000 / icoAndPOfPart;
ert.mint(BountyFund, bountyPart * totalAmount / 10000); // 1.5% for Bounty
ert.mint(AdvisorsFund, advisorsPart * totalAmount / 10000); // 3.89% for Advisors
ert.mint(TeamFund, teamPart * totalAmount / 10000); // 10% for Eristica team
ert.mint(ChallengeFund, challengePart * totalAmount / 10000); // 10% for Challenge Fund
ert.defrost();
statusICO = StatusICO.Finished;
LogFinishICO(BountyFund, AdvisorsFund, TeamFund, ChallengeFund);
}
// function that buys tokens when investor sends ETH to address of ICO
function() external payable {
buy(msg.sender, msg.value * Token_Price);
}
// function for buying tokens to investors who paid in other cryptos
function buyForInvestor(address _investor, uint _ertValue, string _txHash) external controllersOnly {
buy(_investor, _ertValue);
LogBuyForInvestor(_investor, _ertValue, _txHash);
}
//function for buying tokens for presale investors
function replaceToken(address _investor) managerOnly{
require(statusICO != StatusICO.Finished);
uint spertTokens = presale.balanceOf(_investor);
require(spertTokens > 0);
presale.burnTokens(_investor);
ert.mint(_investor, spertTokens);
LogReplaceToken(_investor, spertTokens);
}
// internal function for buying tokens
function buy(address _investor, uint _ertValue) internal {
require(statusICO == StatusICO.Started);
require(_ertValue > 0);
require(Sold + _ertValue <= Tokens_For_Sale);
ert.mint(_investor, _ertValue);
Sold = Sold.add(_ertValue);
}
//function to withdraw ETH from smart contract
function withdrawEther(uint256 _value) external managerOnly {
require(statusICO == StatusICO.Finished);
Company.transfer(_value);
}
}
contract ERT is ERC20 {
using SafeMath for uint;
string public name = "Eristica TOKEN";
string public symbol = "ERT";
uint public decimals = 18;
address public ico;
event Burn(address indexed from, uint256 value);
bool public tokensAreFrozen = true;
modifier icoOnly { require(msg.sender == ico); _; }
function ERT(address _ico) {
ico = _ico;
}
function mint(address _holder, uint _value) external icoOnly {
require(_value != 0);
balances[_holder] = balances[_holder].add(_value);
totalSupply = totalSupply.add(_value);
Transfer(0x0, _holder, _value);
}
function defrost() external icoOnly {
tokensAreFrozen = false;
}
function burn(uint256 _value) {
require(!tokensAreFrozen);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
}
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) returns (bool) {
require(!tokensAreFrozen);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) returns (bool) {
require(!tokensAreFrozen);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _amount) 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((_amount == 0) || (allowed[msg.sender][_spender] == 0));
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];
}
} | Tokens for Sale (HardCap)
| uint public constant Tokens_For_Sale = 482500000*1e18; | 12,871,451 | [
1,
5157,
364,
348,
5349,
261,
29601,
4664,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
1071,
5381,
13899,
67,
1290,
67,
30746,
273,
9934,
2947,
11706,
14,
21,
73,
2643,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.5.4<0.6.0;
contract ERC20Detailed {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
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);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
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);
}
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);
}
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);
}
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);
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library MultiSigAction {
struct Action {
uint8 actionType;
address callbackAddress;
string callbackSig;
bytes callbackData;
uint8 quorum;
address requestedBy;
address rejectedBy;
mapping(address => bool) approvedBy;
uint8 numOfApprovals;
bool rejected;
bool failed;
}
function init(
Action storage _self,
uint8 _actionType,
address _callbackAddress,
string memory _callbackSig,
bytes memory _callbackData,
uint8 _quorum
) internal {
_self.actionType = _actionType;
_self.callbackAddress = _callbackAddress;
_self.callbackSig = _callbackSig;
_self.callbackData = _callbackData;
_self.quorum = _quorum;
_self.requestedBy = msg.sender;
}
function approve(Action storage _self) internal {
require(!_self.rejected, "CANNOT_APPROVE_REJECTED");
require(!_self.failed, "CANNOT_APPROVE_FAILED");
require(!_self.approvedBy[msg.sender], "CANNOT_APPROVE_AGAIN");
require(!isCompleted(_self), "CANNOT_APPROVE_COMPLETED");
_self.approvedBy[msg.sender] = true;
_self.numOfApprovals++;
}
function reject(Action storage _self) internal {
require(!_self.approvedBy[msg.sender], "CANNOT_REJECT_APPROVED");
require(!_self.failed, "CANNOT_REJECT_FAILED");
require(!_self.rejected, "CANNOT_REJECT_REJECTED");
require(!isCompleted(_self), "CANNOT_REJECT_COMPLETED");
_self.rejectedBy = msg.sender;
_self.rejected = true;
}
function complete(Action storage _self) internal {
require(!_self.rejected, "CANNOT_COMPLETE_REJECTED");
require(!_self.failed, "CANNOT_COMPLETE_FAILED");
require(isCompleted(_self), "CANNNOT_COMPLETE_AGAIN");
// solium-disable-next-line security/no-low-level-calls
(bool _success, ) = _self.callbackAddress.call(
abi.encodePacked(bytes4(keccak256(bytes(_self.callbackSig))), _self.callbackData)
);
if (!_success) {
_self.failed = true;
}
}
function isCompleted(Action storage _self) internal view returns (bool) {
return _self.numOfApprovals >= _self.quorum && !_self.failed;
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
contract ERC20Extended is Ownable, ERC20, ERC20Detailed {
constructor(string memory _name, string memory _symbol, uint8 _decimals)
public
ERC20Detailed(_name, _symbol, _decimals)
{}
function burn(uint256 _value) public onlyOwner returns (bool) {
_burn(msg.sender, _value);
return true;
}
function mint(address _to, uint256 _value) public onlyOwner returns (bool) {
_mint(_to, _value);
return true;
}
}
contract MultiSigAdministration {
event TenantRegistered(
address indexed tenant,
address[] creators,
address[] admins,
uint8 quorum
);
event ActionInitiated(address indexed tenant, uint256 indexed id, address initiatedBy);
event ActionApproved(address indexed tenant, uint256 indexed id, address approvedBy);
event ActionRejected(address indexed tenant, uint256 indexed id, address rejectedBy);
event ActionCompleted(address indexed tenant, uint256 indexed id);
event ActionFailed(address indexed tenant, uint256 indexed id);
using MultiSigAction for MultiSigAction.Action;
enum AdminAction {ADD_ADMIN, REMOVE_ADMIN, CHANGE_QUORUM, ADD_CREATOR, REMOVE_CREATOR}
uint8 private constant OTHER_ACTION = uint8(AdminAction.REMOVE_CREATOR) + 1;
mapping(address => uint256) public numOfActions;
mapping(address => mapping(address => bool)) public isAdmin;
mapping(address => uint8) public numOfAdmins;
mapping(address => mapping(address => bool)) public isCreator;
mapping(address => uint8) public quorums;
mapping(address => bool) public isRegistered;
mapping(address => uint256) public minValidActionId;
mapping(address => mapping(uint256 => MultiSigAction.Action)) private actions;
modifier onlyAdminOf(address _tenant) {
require(isAdmin[_tenant][msg.sender], "ONLY_ADMIN_OF_TENANT");
_;
}
modifier onlyAdminOrCreatorOf(address _tenant) {
require(
isAdmin[_tenant][msg.sender] || isCreator[_tenant][msg.sender],
"ONLY_ADMIN_OR_CREATOR_OF_TENANT"
);
_;
}
modifier onlyRegistered(address _tenant) {
require(isRegistered[_tenant], "ONLY_REGISTERED_TENANT");
_;
}
modifier onlyMe() {
require(msg.sender == address(this), "ONLY_INTERNAL");
_;
}
modifier onlyExistingAction(address _tenant, uint256 _id) {
require(_id <= numOfActions[_tenant], "ONLY_EXISTING_ACTION");
require(_id > 0, "ONLY_EXISTING_ACTION");
_;
}
constructor() public {}
/* Public Functions - Start */
function register(
address _tenant,
address[] memory _creators,
address[] memory _admins,
uint8 _quorum
) public returns (bool success) {
require(
msg.sender == _tenant || msg.sender == Ownable(_tenant).owner(),
"ONLY_TENANT_OR_TENANT_OWNER"
);
return _register(_tenant, _creators, _admins, _quorum);
}
function initiateAdminAction(
address _tenant,
AdminAction _adminAction,
bytes memory _callbackData
) public onlyRegistered(_tenant) onlyAdminOf(_tenant) returns (uint256 id) {
string memory _callbackSig = _getAdminActionCallbackSig(_adminAction);
uint256 _id = _initiateAction(
uint8(_adminAction),
_tenant,
address(this),
_callbackSig,
abi.encodePacked(abi.encode(_tenant), _callbackData)
);
_approveAction(_tenant, _id);
return _id;
}
function initiateAction(address _tenant, string memory _callbackSig, bytes memory _callbackData)
public
onlyRegistered(_tenant)
onlyAdminOrCreatorOf(_tenant)
returns (uint256 id)
{
uint256 _id = _initiateAction(OTHER_ACTION, _tenant, _tenant, _callbackSig, _callbackData);
if (isAdmin[_tenant][msg.sender]) {
_approveAction(_tenant, _id);
}
return _id;
}
function approveAction(address _tenant, uint256 _id)
public
onlyRegistered(_tenant)
onlyAdminOf(_tenant)
onlyExistingAction(_tenant, _id)
returns (bool success)
{
return _approveAction(_tenant, _id);
}
function rejectAction(address _tenant, uint256 _id)
public
onlyRegistered(_tenant)
onlyAdminOrCreatorOf(_tenant)
onlyExistingAction(_tenant, _id)
returns (bool success)
{
return _rejectAction(_tenant, _id);
}
function addAdmin(address _tenant, address _admin, bool _increaseQuorum) public onlyMe {
minValidActionId[_tenant] = numOfActions[_tenant] + 1;
_addAdmin(_tenant, _admin);
if (_increaseQuorum) {
uint8 _quorum = quorums[_tenant];
uint8 _newQuorum = _quorum + 1;
require(_newQuorum > _quorum, "OVERFLOW");
_changeQuorum(_tenant, _newQuorum);
}
}
function removeAdmin(address _tenant, address _admin, bool _decreaseQuorum) public onlyMe {
uint8 _quorum = quorums[_tenant];
if (_decreaseQuorum && _quorum > 1) {
_changeQuorum(_tenant, _quorum - 1);
}
minValidActionId[_tenant] = numOfActions[_tenant] + 1;
_removeAdmin(_tenant, _admin);
}
function changeQuorum(address _tenant, uint8 _quorum) public onlyMe {
minValidActionId[_tenant] = numOfActions[_tenant] + 1;
_changeQuorum(_tenant, _quorum);
}
function addCreator(address _tenant, address _creator) public onlyMe {
_addCreator(_tenant, _creator);
}
function removeCreator(address _tenant, address _creator) public onlyMe {
_removeCreator(_tenant, _creator);
}
function getAction(address _tenant, uint256 _id)
public
view
returns (
bool isAdminAction,
string memory callbackSig,
bytes memory callbackData,
uint8 quorum,
address requestedBy,
address rejectedBy,
uint8 numOfApprovals,
bool rejected,
bool failed,
bool completed,
bool valid
)
{
MultiSigAction.Action storage _action = _getAction(_tenant, _id);
isAdminAction = _action.callbackAddress == address(this);
callbackSig = _action.callbackSig;
callbackData = _action.callbackData;
quorum = _action.quorum;
requestedBy = _action.requestedBy;
rejectedBy = _action.rejectedBy;
numOfApprovals = _action.numOfApprovals;
rejected = _action.rejected;
failed = _action.failed;
completed = _action.isCompleted();
valid = _isActionValid(_tenant, _id);
}
function hasApprovedBy(address _tenant, uint256 _id, address _admin)
public
view
returns (bool approvedBy)
{
approvedBy = _getAction(_tenant, _id).approvedBy[_admin];
}
/* Public Functions - End */
/* Private Functions - Start */
function _getAction(address _tenant, uint256 _id)
private
view
returns (MultiSigAction.Action storage)
{
return actions[_tenant][_id];
}
function _isActionValid(address _tenant, uint256 _id) private view returns (bool) {
return _id >= minValidActionId[_tenant];
}
function _getAdminActionCallbackSig(AdminAction _adminAction)
private
pure
returns (string memory)
{
if (_adminAction == AdminAction.ADD_ADMIN) {
return "addAdmin(address,address,bool)";
}
if (_adminAction == AdminAction.REMOVE_ADMIN) {
return "removeAdmin(address,address,bool)";
}
if (_adminAction == AdminAction.CHANGE_QUORUM) {
return "changeQuorum(address,uint8)";
}
if (_adminAction == AdminAction.ADD_CREATOR) {
return "addCreator(address,address)";
}
return "removeCreator(address,address)";
}
function _addCreator(address _tenant, address _creator) private {
require(_creator != address(this), "INVALID_CREATOR");
require(!isAdmin[_tenant][_creator], "ALREADY_ADMIN");
require(!isCreator[_tenant][_creator], "ALREADY_CREATOR");
isCreator[_tenant][_creator] = true;
}
function _removeCreator(address _tenant, address _creator) private {
require(isCreator[_tenant][_creator], "NOT_CREATOR");
isCreator[_tenant][_creator] = false;
}
function _addAdmin(address _tenant, address _admin) private {
require(_admin != address(this), "INVALID_ADMIN");
require(!isAdmin[_tenant][_admin], "ALREADY_ADMIN");
require(!isCreator[_tenant][_admin], "ALREADY_CREATOR");
require(numOfAdmins[_tenant] + 1 > numOfAdmins[_tenant], "OVERFLOW");
numOfAdmins[_tenant]++;
isAdmin[_tenant][_admin] = true;
}
function _removeAdmin(address _tenant, address _admin) private {
require(isAdmin[_tenant][_admin], "NOT_ADMIN");
require(--numOfAdmins[_tenant] >= quorums[_tenant], "TOO_FEW_ADMINS");
isAdmin[_tenant][_admin] = false;
}
function _changeQuorum(address _tenant, uint8 _quorum) private {
require(_quorum <= numOfAdmins[_tenant], "QUORUM_TOO_BIG");
require(_quorum > 0, "QUORUM_ZERO");
quorums[_tenant] = _quorum;
}
function _register(
address _tenant,
address[] memory _creators,
address[] memory _admins,
uint8 _quorum
) private returns (bool) {
require(_tenant != address(this), "INVALID_TENANT");
require(!isRegistered[_tenant], "ALREADY_REGISTERED");
for (uint8 i = 0; i < _admins.length; i++) {
_addAdmin(_tenant, _admins[i]);
}
_changeQuorum(_tenant, _quorum);
for (uint8 i = 0; i < _creators.length; i++) {
_addCreator(_tenant, _creators[i]);
}
isRegistered[_tenant] = true;
emit TenantRegistered(_tenant, _creators, _admins, _quorum);
return true;
}
function _initiateAction(
uint8 _actionType,
address _tenant,
address _callbackAddress,
string memory _callbackSig,
bytes memory _callbackData
) private returns (uint256) {
uint256 _id = ++numOfActions[_tenant];
uint8 _quorum = quorums[_tenant];
if (_actionType == uint8(AdminAction.REMOVE_ADMIN)) {
require(numOfAdmins[_tenant] > 1, "TOO_FEW_ADMINS");
if (_quorum == numOfAdmins[_tenant] && _quorum > 2) {
_quorum = numOfAdmins[_tenant] - 1;
}
}
_getAction(_tenant, _id).init(
_actionType,
_callbackAddress,
_callbackSig,
_callbackData,
_quorum
);
emit ActionInitiated(_tenant, _id, msg.sender);
return _id;
}
function _approveAction(address _tenant, uint256 _id) private returns (bool) {
require(_isActionValid(_tenant, _id), "ACTION_INVALIDATED");
MultiSigAction.Action storage _action = _getAction(_tenant, _id);
_action.approve();
emit ActionApproved(_tenant, _id, msg.sender);
if (_action.isCompleted()) {
_action.complete();
if (_action.failed) {
emit ActionFailed(_tenant, _id);
} else {
emit ActionCompleted(_tenant, _id);
}
}
return true;
}
function _rejectAction(address _tenant, uint256 _id) private returns (bool) {
MultiSigAction.Action storage _action = _getAction(_tenant, _id);
if (isCreator[_tenant][msg.sender]) {
require(msg.sender == _action.requestedBy, "CREATOR_REJECT_NOT_REQUESTOR");
}
if (_action.actionType == uint8(AdminAction.REMOVE_ADMIN)) {
(, address _admin, ) = abi.decode(_action.callbackData, (address, address, bool));
require(_admin != msg.sender, "CANNOT_REJECT_ITS_OWN_REMOVAL");
}
_action.reject();
emit ActionRejected(_tenant, _id, msg.sender);
return true;
}
/* Private Functions - End */
}
contract MultiSigProxyOwner {
event BurnRequested(address indexed owner, uint256 value);
event BurnCanceled(address indexed owner);
event BurnMinSet(uint256 burnMin);
struct BurnRequest {
uint256 actionId;
uint256 value;
}
uint256 public burnMin;
mapping(address => BurnRequest) public burnRequests;
ERC20Extended private token;
MultiSigAdministration private multiSigAdmin;
address[] private creators;
modifier onlyMultiSigAdministration {
require(msg.sender == address(multiSigAdmin));
_;
}
constructor(
address _token,
address _multiSigAdmin,
address[] memory _admins,
uint8 _quorum,
uint256 _burnMin
) public {
token = ERC20Extended(_token);
multiSigAdmin = MultiSigAdministration(_multiSigAdmin);
burnMin = _burnMin;
creators.push(address(this));
multiSigAdmin.register(address(this), creators, _admins, _quorum);
}
function requestBurn(uint256 _value) public returns (bool) {
require(!_burnRequestExist(msg.sender), "BURN_REQUEST_EXISTS");
require(_value >= burnMin, "SMALLER_THAN_MIN_BURN_AMOUNT");
token.transferFrom(msg.sender, address(this), _value);
burnRequests[msg.sender].value = _value;
burnRequests[msg.sender].actionId = multiSigAdmin.initiateAction(
address(this),
"burn(address,uint256)",
abi.encode(msg.sender, _value)
);
emit BurnRequested(msg.sender, _value);
return true;
}
function cancelBurn() public returns (bool) {
uint256 _actionId = burnRequests[msg.sender].actionId;
uint256 _value = burnRequests[msg.sender].value;
_deleteBurnRequest(msg.sender);
// solium-disable-next-line security/no-low-level-calls
(bool _success, ) = address(multiSigAdmin).call(
abi.encodeWithSignature("rejectAction(address,uint256)", address(this), _actionId)
);
_success;
token.transfer(msg.sender, _value);
emit BurnCanceled(msg.sender);
return true;
}
function burn(address _owner, uint256 _value) public onlyMultiSigAdministration returns (bool) {
require(burnRequests[_owner].value == _value, "BURN_VALUE_MISMATCH");
_deleteBurnRequest(_owner);
token.burn(_value);
return true;
}
function mint(address _to, uint256 _value) public onlyMultiSigAdministration returns (bool) {
return token.mint(_to, _value);
}
function transferOwnership(address _newOwner) public onlyMultiSigAdministration returns (bool) {
token.transferOwnership(_newOwner);
return true;
}
function setBurnMin(uint256 _burnMin) public onlyMultiSigAdministration returns (bool) {
return _setBurnMin(_burnMin);
}
function _setBurnMin(uint256 _burnMin) internal returns (bool) {
burnMin = _burnMin;
emit BurnMinSet(_burnMin);
return true;
}
function _burnRequestExist(address _owner) internal view returns (bool) {
return burnRequests[_owner].actionId != 0;
}
function _deleteBurnRequest(address _owner) internal returns (bool) {
require(_burnRequestExist(_owner), "NO_BURN_REQUEST_EXISTS");
burnRequests[_owner].actionId = 0;
burnRequests[_owner].value = 0;
return true;
}
} | solium-disable-next-line security/no-low-level-calls | function cancelBurn() public returns (bool) {
uint256 _actionId = burnRequests[msg.sender].actionId;
uint256 _value = burnRequests[msg.sender].value;
_deleteBurnRequest(msg.sender);
(bool _success, ) = address(multiSigAdmin).call(
abi.encodeWithSignature("rejectAction(address,uint256)", address(this), _actionId)
);
_success;
token.transfer(msg.sender, _value);
emit BurnCanceled(msg.sender);
return true;
}
| 12,770,710 | [
1,
18281,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
821,
17,
2815,
17,
12550,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
3755,
38,
321,
1435,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2254,
5034,
389,
1128,
548,
273,
18305,
6421,
63,
3576,
18,
15330,
8009,
1128,
548,
31,
203,
565,
2254,
5034,
389,
1132,
273,
18305,
6421,
63,
3576,
18,
15330,
8009,
1132,
31,
203,
565,
389,
3733,
38,
321,
691,
12,
3576,
18,
15330,
1769,
203,
203,
565,
261,
6430,
389,
4768,
16,
262,
273,
1758,
12,
7027,
8267,
4446,
2934,
1991,
12,
203,
1377,
24126,
18,
3015,
1190,
5374,
2932,
24163,
1803,
12,
2867,
16,
11890,
5034,
2225,
16,
1758,
12,
2211,
3631,
389,
1128,
548,
13,
203,
565,
11272,
203,
565,
389,
4768,
31,
203,
565,
1147,
18,
13866,
12,
3576,
18,
15330,
16,
389,
1132,
1769,
203,
203,
565,
3626,
605,
321,
23163,
12,
3576,
18,
15330,
1769,
203,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x9642c7026822391100a4773d7aA597AE18ECE7dd/sources/Synthetix.sol | Insufficient balance will be handled by the safe subtraction. Emit a standard ERC20 transfer event If the recipient is a contract, we need to call tokenFallback on it so they can do ERC223 actions when receiving our tokens. Unlike the standard, however, we don't revert if the recipient contract doesn't implement tokenFallback. | function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the contract");
require(to != address(proxy), "Cannot transfer to the proxy");
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
emitTransfer(from, to, value);
callTokenFallbackIfNeeded(from, to, value, data);
return true;
}
| 16,502,828 | [
1,
5048,
11339,
11013,
903,
506,
7681,
635,
326,
4183,
720,
25693,
18,
16008,
279,
4529,
4232,
39,
3462,
7412,
871,
971,
326,
8027,
353,
279,
6835,
16,
732,
1608,
358,
745,
1147,
12355,
603,
518,
1427,
2898,
848,
741,
4232,
39,
3787,
23,
4209,
1347,
15847,
3134,
2430,
18,
25448,
326,
4529,
16,
14025,
16,
732,
2727,
1404,
15226,
309,
326,
8027,
6835,
3302,
1404,
2348,
1147,
12355,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
7236,
5912,
12,
2867,
628,
16,
1758,
358,
16,
2254,
460,
16,
1731,
501,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
4515,
7412,
358,
326,
374,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
2211,
3631,
315,
4515,
7412,
358,
326,
6835,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
5656,
3631,
315,
4515,
7412,
358,
326,
2889,
8863,
203,
203,
3639,
1147,
1119,
18,
542,
13937,
951,
12,
2080,
16,
1147,
1119,
18,
12296,
951,
12,
2080,
2934,
1717,
12,
1132,
10019,
203,
3639,
1147,
1119,
18,
542,
13937,
951,
12,
869,
16,
1147,
1119,
18,
12296,
951,
12,
869,
2934,
1289,
12,
1132,
10019,
203,
203,
3639,
3626,
5912,
12,
2080,
16,
358,
16,
460,
1769,
203,
203,
3639,
745,
1345,
12355,
18299,
12,
2080,
16,
358,
16,
460,
16,
501,
1769,
203,
540,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/*
* @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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
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 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.3._
*/
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.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @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 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) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
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(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(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(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
/**
* @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--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
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 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;
}
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
/**
* @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 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 override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).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(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, 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 returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view 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 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 = 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 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 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 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 returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || 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 = ownerOf(tokenId);
_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(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);
_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(ownerOf(tokenId), to, tokenId);
}
/**
* @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 { }
}
/**
* @title ERC721SWAPO
* This mock just provides a public safeMint, mint, and burn functions for testing purposes
*/
contract ERC721SWAPO is ERC721, Ownable {
constructor (string memory name, string memory symbol) public ERC721(name, symbol) { }
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
function setTokenURI(uint256 tokenId, string memory uri) public {
_setTokenURI(tokenId, uri);
}
function setBaseURI(string memory baseURI) public {
_setBaseURI(baseURI);
}
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
function safeMint(address to, uint256 tokenId) public {
_safeMint(to, tokenId);
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public {
_safeMint(to, tokenId, _data);
}
function burn(uint256 tokenId) public {
_burn(tokenId);
}
} | * @title ERC721SWAPO This mock just provides a public safeMint, mint, and burn functions for testing purposes/ | contract ERC721SWAPO is ERC721, Ownable {
constructor (string memory name, string memory symbol) public ERC721(name, symbol) { }
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
function setTokenURI(uint256 tokenId, string memory uri) public {
_setTokenURI(tokenId, uri);
}
function setBaseURI(string memory baseURI) public {
_setBaseURI(baseURI);
}
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
function safeMint(address to, uint256 tokenId) public {
_safeMint(to, tokenId);
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public {
_safeMint(to, tokenId, _data);
}
function burn(uint256 tokenId) public {
_burn(tokenId);
}
} | 13,769,989 | [
1,
654,
39,
27,
5340,
18746,
2203,
51,
1220,
5416,
2537,
8121,
279,
1071,
4183,
49,
474,
16,
312,
474,
16,
471,
18305,
4186,
364,
7769,
13694,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
27,
5340,
18746,
2203,
51,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
288,
203,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
4232,
39,
27,
5340,
12,
529,
16,
3273,
13,
288,
289,
203,
565,
445,
1704,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
1808,
12,
2316,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
22629,
3098,
12,
11890,
5034,
1147,
548,
16,
533,
3778,
2003,
13,
1071,
288,
203,
3639,
389,
542,
1345,
3098,
12,
2316,
548,
16,
2003,
1769,
203,
565,
289,
203,
203,
565,
445,
26435,
3098,
12,
1080,
3778,
1026,
3098,
13,
1071,
288,
203,
3639,
389,
542,
2171,
3098,
12,
1969,
3098,
1769,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
288,
203,
3639,
389,
81,
474,
12,
869,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
4183,
49,
474,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
288,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
4183,
49,
474,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
16,
1731,
3778,
389,
892,
13,
1071,
288,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
1147,
548,
16,
389,
892,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
11890,
5034,
1147,
548,
13,
1071,
288,
203,
3639,
389,
70,
321,
2
]
|
//pragma solidity ^0.5.2;
pragma solidity >=0.4.22 <0.6.0;
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @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);
}
/// @title Shared constants used throughout the Cheeze Wizards contracts
contract WizardConstants {
// Wizards normally have their affinity set when they are first created,
// but for example Exclusive Wizards can be created with no set affinity.
// In this case the affinity can be set by the owner.
uint8 internal constant ELEMENT_NOTSET = 0; //000
// A neutral Wizard has no particular strength or weakness with specific
// elements.
uint8 internal constant ELEMENT_NEUTRAL = 1; //001
// The fire, water and wind elements are used both to reflect an affinity
// of Elemental Wizards for a specific element, and as the moves a
// Wizard can make during a duel.
// Note thta if these values change then `moveMask` and `moveDelta` in
// ThreeAffinityDuelResolver would need to be updated accordingly.
uint8 internal constant ELEMENT_FIRE = 2; //010
uint8 internal constant ELEMENT_WATER = 3; //011
uint8 internal constant ELEMENT_WIND = 4; //100
uint8 internal constant MAX_ELEMENT = ELEMENT_WIND;
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
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 memory data) public;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/*
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
/// Utility library of inline functions on address payables.
/// Modified from original by OpenZeppelin.
contract Address {
/// @notice Returns whether the target address is a contract.
/// @dev This function will return false if invoked during the constructor of a contract,
/// as the code is not actually created until after the constructor finishes.
/// @param account address of the account to check
/// @return whether the target address is a contract
function isContract(address account) 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.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
/**
* @title WizardPresaleNFT
* @notice The basic ERC-721 functionality for storing the presale Wizard NFTs.
* Derived from: https://github.com/OpenZeppelin/openzeppelin-solidity/tree/v2.2.0
*/
contract WizardPresaleNFT is ERC165, IERC721, Address {
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);
/// @notice Emitted when a wizard token is created.
event WizardSummoned(uint256 indexed tokenId, uint8 element, uint256 power);
/// @notice Emitted when a wizard change element. Should only happen once and for wizards
/// that previously had the element undefined.
event WizardAlignmentAssigned(uint256 indexed tokenId, uint8 element);
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02;
/// @dev The presale Wizard structure.
/// Fits in one word
struct Wizard {
// NOTE: Changing the order or meaning of any of these fields requires an update
// to the _createWizard() function which assumes a specific order for these fields.
uint8 affinity;
uint88 power;
address owner;
}
// Mapping from Wizard ID to Wizard struct
mapping (uint256 => Wizard) public _wizardsById;
// Mapping from token ID to approved address
mapping (uint256 => address) private _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)) private _operatorApprovals;
bytes4 private constant _INTERFACE_ID_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)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @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), "ERC721: balance query for the zero address");
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 address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _wizardsById[tokenId].owner;
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
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, "ERC721: approve to caller");
_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 {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(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 {
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 memory _data) public {
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _wizardsById[tokenId].owner;
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner]--;
// delete the entire object to recover the most gas
delete _wizardsById[tokenId];
// required for ERC721 compatibility
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from]--;
_ownedTokensCount[to]++;
_wizardsById[tokenId].owner = to;
emit Transfer(from, to, tokenId);
}
/**
* @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 bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!isContract(to)) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/// @title WizardPresaleInterface
/// @notice This interface represents the single method that the final tournament and master Wizard contracts
/// will use to import the presale wizards when those contracts have been finalized a released on
/// mainnet. Once all presale Wizards have been absorbed, this temporary pre-sale contract can be
/// destroyed.
contract WizardPresaleInterface {
// See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md on how
// to calculate this
bytes4 public constant _INTERFACE_ID_WIZARDPRESALE = 0x4df71efb;
/// @notice This function is used to bring a presale Wizard into the final contracts. It can
/// ONLY be called by the official gatekeeper contract (as set by the Owner of the presale
/// contract). It does a number of things:
/// 1. Check that the presale Wizard exists, and has not already been absorbed
/// 2. Transfer the Eth used to create the presale Wizard to the caller
/// 3. Mark the Wizard as having been absorbed, reclaiming the storage used by the presale info
/// 4. Return the Wizard information (its owner, minting price, and elemental alignment)
/// @param id the id of the presale Wizard to be absorbed
function absorbWizard(uint256 id) external returns (address owner, uint256 power, uint8 affinity);
/// @notice A convenience function that allows multiple Wizards to be moved to the final contracts
/// simultaneously, works the same as the previous function, but in a batch.
/// @param ids An array of ids indicating which presale Wizards are to be absorbed
function absorbWizardMulti(uint256[] calldata ids) external
returns (address[] memory owners, uint256[] memory powers, uint8[] memory affinities);
function powerToCost(uint256 power) public pure returns (uint256 cost);
function costToPower(uint256 cost) public pure returns (uint256 power);
}
/// @title WizardPresale - Making Cheeze Wizards available for sale!
/// @notice Allows for the creation and sale of Cheeze Wizards before the final tournament
/// contract has been reviewed and released on mainnet. There are three main types
/// of Wizards that are managed by this contract:
/// - Neutral Wizards: Available in unlimited quantities and all have the same
/// innate power. Don't have a natural affinity for any particular elemental
/// spell... or the corresponding weakness!
/// - Elemental Wizards: Available in unlimited quantities, but with a steadily increasing
/// power; the power of an Elemental Wizard is always _slightly_ higher than the power
/// of the previously created Elemental Wizard. Each Elemental Wizard has an Elemental
/// Affinity that gives it a power multiplier when using the associated spell, but also
/// gives it a weakness for the opposing element.
/// - Exclusive Wizards: Only available in VERY limited quantities, with a hard cap set at
/// contract creation time. Exclusive Wizards can ONLY be created by the Guild Master
/// address (the address that created this contract), and are assigned the first N
/// Wizard IDs, starting with 1 (where N is the hard cap on Exclusive Wizards). The first
/// non-exclusive Wizard is assigned the ID N+1. Exclusive Wizards have no starting
/// affinity, and their owners much choose an affinity before they can be entered into a
/// Battle. The affinity CAN NOT CHANGE once it has been selected. The power of Exclusive
/// Wizards is not set by the Guild Master and is not required to follow any pattern (although
/// it can't be lower than the power of Neutral Wizards).
contract WizardPresale is WizardPresaleNFT, WizardPresaleInterface, WizardConstants {
/// @dev The ratio between the cost of a Wizard (in wei) and the power of the wizard.
/// power = cost / POWER_SCALE
/// cost = power * POWER_SCALE
uint256 private constant POWER_SCALE = 1000;
/// @dev The unit conversion for tenths of basis points
uint256 private constant TENTH_BASIS_POINTS = 100000;
/// @dev The address used to create this smart contract, has permission to conjure Exclusive Wizards,
/// set the gatekeeper address, and destroy this contract once the sale is finished and all Presale
/// Wizards have been absorbed into the main contracts.
address payable public guildmaster;
/// @dev The start block and duration (in blocks) of the sale.
/// ACT NOW! For a limited time only!
uint256 public saleStartBlock;
uint256 public saleDuration;
/// @dev The cost of Neutral Wizards (in wei).
uint256 public neutralWizardCost;
/// @dev The cost of the _next_ Elemental Wizard (in wei); increases with each Elemental Wizard sold
uint256 public elementalWizardCost;
/// @dev The increment ratio in price between sequential Elemental Wizards, multiplied by 100k for
/// greater granularity (0 == 0% increase, 100000 == 100% increase, 100 = 0.1% increase, etc.)
/// NOTE: This is NOT percentage points, or basis points. It's tenths of a basis point.
uint256 public elementalWizardIncrement;
/// @dev The hard cap on how many Exclusive Wizards can be created
uint256 public maxExclusives;
/// @dev The ID number of the next Wizard to be created (Neutral or Elemental)
uint256 public nextWizardId;
/// @dev The address of the Gatekeeper for the tournament, initially set to address(0).
/// To be set by the Guild Master when the final Tournament Contract is deployed on mainnet
address payable public gatekeeper;
/// @notice Emitted whenever the start of the sale changes.
event StartBlockChanged(uint256 oldStartBlock, uint256 newStartBlock);
/// @param startingCost The minimum cost of a Wizard, used as the price for all Neutral Wizards, and the
/// cost of the first Elemental Wizard. Also used as a minimum value for Exclusive Wizards.
/// @param costIncremement The rate (in tenths of a basis point) at which the price of Elemental Wizards increases
/// @param exclusiveCount The hard cap on Exclusive Wizards, also dictates the ID of the first non-Exclusive
/// @param startBlock The starting block of the presale.
/// @param duration The duration of the presale. Not changeable!
constructor(uint128 startingCost,
uint16 costIncremement,
uint256 exclusiveCount,
uint128 startBlock,
uint128 duration) public
{
require(startBlock > block.number, "Start must be greater than current block");
guildmaster = msg.sender;
saleStartBlock = startBlock;
saleDuration = duration;
neutralWizardCost = startingCost;
elementalWizardCost = startingCost;
elementalWizardIncrement = costIncremement;
maxExclusives = exclusiveCount;
nextWizardId = exclusiveCount + 1;
_registerInterface(_INTERFACE_ID_WIZARDPRESALE);
}
/// @dev Throws if called by any account other than the gatekeeper.
modifier onlyGatekeeper() {
require(msg.sender == gatekeeper, "Must be gatekeeper");
_;
}
/// @dev Throws if called by any account other than the guildmaster.
modifier onlyGuildmaster() {
require(msg.sender == guildmaster, "Must be guildmaster");
_;
}
/// @dev Checks to see that the current block number is within the range
/// [saleStartBlock, saleStartBlock + saleDuraction) indicating that the sale
/// is currently active
modifier onlyDuringSale() {
// The addtion of start and duration can't overflow since they can only be set from
// 128-bit arguments.
require(block.number >= saleStartBlock, "Sale not open yet");
require(block.number < saleStartBlock + saleDuration, "Sale closed");
_;
}
/// @dev Sets the address of the Gatekeeper contract once the final Tournament contract is live.
/// Can only be set once.
/// @param gc The gatekeeper address to set
function setGatekeeper(address payable gc) external onlyGuildmaster {
require(gatekeeper == address(0) && gc != address(0), "Can only set once and must not be 0");
gatekeeper = gc;
}
/// @dev Updates the start block of the sale. The sale can only be postponed; it can't be made earlier.
/// @param newStart the new start block.
function postponeSale(uint128 newStart) external onlyGuildmaster {
require(block.number < saleStartBlock, "Sale start time only adjustable before previous start time");
require(newStart > saleStartBlock, "New start time must be later than previous start time");
emit StartBlockChanged(saleStartBlock, newStart);
saleStartBlock = newStart;
}
/// @dev Returns true iff the sale is currently active
function isDuringSale() external view returns (bool) {
return (block.number >= saleStartBlock && block.number < saleStartBlock + saleDuration);
}
/// @dev Convenience method for getting a presale wizard's data
/// @param id The wizard id
function getWizard(uint256 id) public view returns (address owner, uint88 power, uint8 affinity) {
Wizard memory wizard = _wizardsById[id];
(owner, power, affinity) = (wizard.owner, wizard.power, wizard.affinity);
require(wizard.owner != address(0), "Wizard does not exist");
}
/// @param cost The price of the wizard in wei
/// @return The power of the wizard (left as uint256)
function costToPower(uint256 cost) public pure returns (uint256 power) {
return cost / POWER_SCALE;
}
/// @param power The power of the wizard
/// @return The cost of the wizard in wei
function powerToCost(uint256 power) public pure returns (uint256 cost) {
return power * POWER_SCALE;
}
/// @notice This function is used to bring a presale Wizard into the final contracts. It can
/// ONLY be called by the official gatekeeper contract (as set by the Owner of the presale
/// contract). It does a number of things:
/// 1. Check that the presale Wizard exists, and has not already been absorbed
/// 2. Transfer the Eth used to create the presale Wizard to the caller
/// 3. Mark the Wizard as having been absorbed, reclaiming the storage used by the presale info
/// 4. Return the Wizard information (its owner, minting price, and elemental alignment)
/// @param id the id of the presale Wizard to be absorbed
function absorbWizard(uint256 id) external onlyGatekeeper returns (address owner, uint256 power, uint8 affinity) {
(owner, power, affinity) = getWizard(id);
// Free up the storage used by this wizard
_burn(owner, id);
// send the price paid to the gatekeeper to be used in the tournament prize pool
msg.sender.transfer(powerToCost(power));
}
/// @notice A convenience function that allows multiple Wizards to be moved to the final contracts
/// simultaneously, works the same as the previous function, but in a batch.
/// @param ids An array of ids indicating which presale Wizards are to be absorbed
function absorbWizardMulti(uint256[] calldata ids) external onlyGatekeeper
returns (address[] memory owners, uint256[] memory powers, uint8[] memory affinities)
{
// allocate arrays
owners = new address[](ids.length);
powers = new uint256[](ids.length);
affinities = new uint8[](ids.length);
// The total eth to send (sent in a batch to save gas)
uint256 totalTransfer;
// Put the data for each Wizard into the returned arrays
for (uint256 i = 0; i < ids.length; i++) {
(owners[i], powers[i], affinities[i]) = getWizard(ids[i]);
// Free up the storage used by this wizard
_burn(owners[i], ids[i]);
// add the amount to transfer
totalTransfer += powerToCost(powers[i]);
}
// Send all the eth together
msg.sender.transfer(totalTransfer);
}
/// @dev Internal function to create a new Wizard; reverts if the Wizard ID is taken.
/// NOTE: This function heavily depends on the internal format of the Wizard struct
/// and should always be reassessed if anything about that structure changes.
/// @param tokenId ID of the new Wizard
/// @param owner The address that will own the newly conjured Wizard
/// @param power The power level associated with the new Wizard
/// @param affinity The elemental affinity of the new Wizard
function _createWizard(uint256 tokenId, address owner, uint256 power, uint8 affinity) internal {
require(!_exists(tokenId), "Can't reuse Wizard ID");
require(owner != address(0), "Owner address must exist");
require(power > 0, "Wizard power must be non-0");
require(power < (1<<88), "Wizard power must fit in 88 bits of storage");
require(affinity <= MAX_ELEMENT, "Invalid elemental affinity");
// Create the Wizard!
_wizardsById[tokenId] = Wizard(affinity, uint88(power), owner);
_ownedTokensCount[owner]++;
// Tell the world!
emit Transfer(address(0), owner, tokenId);
emit WizardSummoned(tokenId, affinity, power);
}
/// @dev A private utility function that refunds any overpayment to the sender; smart
/// enough to only send the excess if the amount we are returning is more than the
/// cost of sending it!
/// @dev Warning! This does not check for underflows (msg.value < actualPrice) - so
/// be sure to call this with correct values!
/// @param actualPrice the actual price owed
function _transferRefund(uint256 actualPrice) private {
uint256 refund = msg.value - actualPrice;
// Make sure the amount we're trying to refund is less than the actual cost of sending it!
// See https://github.com/ethereum/wiki/wiki/Subtleties for magic values costs. We can
// safley ignore the 25000 additional gas cost for new accounts, as msg.sender is
// guarunteed to exist at this point!
if (refund > (tx.gasprice * (9000+700))) {
msg.sender.transfer(refund);
}
}
/// @notice Conjures an Exclusive Wizard with a specific element and ID. This can only be done by
/// the Guildmaster, who still has to pay for the power imbued in that Wizard! The power level
/// is inferred by the amount of Eth sent. MUST ONLY BE USED FOR EXTERNAL OWNER ADDRESSES.
/// @param id The ID of the new Wizard; must be in the Exclusive range, and can't already be allocated
/// @param owner The address which will own the new Wizard
/// @param affinity The elemental affinity of the new Wizard, can be ELEMENT_NOTSET for Exclusives!
function conjureExclusiveWizard(uint256 id, address owner, uint8 affinity) public payable onlyGuildmaster {
require(id > 0 && id <= maxExclusives, "Invalid exclusive ID");
_createWizard(id, owner, costToPower(msg.value), affinity);
}
/// @notice Same as conjureExclusiveWizard(), but reverts if the owner address is a smart
/// contract that is not ERC-721 aware.
/// @param id The ID of the new Wizard; must be in the Exclusive range, and can't already be allocated
/// @param owner The address which will own the new Wizard
/// @param affinity The elemental affinity of the new Wizard, can be ELEMENT_NOTSET for Exclusives!
function safeConjureExclusiveWizard(uint256 id, address owner, uint8 affinity) external payable onlyGuildmaster {
conjureExclusiveWizard(id, owner, affinity);
require(_checkOnERC721Received(address(0), owner, id, ""), "Must support erc721");
}
/// @notice Allows for the batch creation of Exclusive Wizards. Same rules apply as above, but the
/// powers are specified instead of being inferred. The message still needs to have enough
/// value to pay for all the newly conjured Wizards! MUST ONLY BE USED FOR EXTERNAL OWNER ADDRESSES.
/// @param ids An array of IDs of the new Wizards
/// @param owners An array of owners
/// @param powers An array of power levels
/// @param affinities An array of elemental affinities
function conjureExclusiveWizardMulti(
uint256[] calldata ids,
address[] calldata owners,
uint256[] calldata powers,
uint8[] calldata affinities) external payable onlyGuildmaster
{
// Ensure the arrays are all of the same length
require(
ids.length == owners.length &&
owners.length == powers.length &&
owners.length == affinities.length,
"Must have equal array lengths"
);
uint256 totalPower = 0;
for (uint256 i = 0; i < ids.length; i++) {
require(ids[i] > 0 && ids[i] <= maxExclusives, "Invalid exclusive ID");
require(affinities[i] <= MAX_ELEMENT, "Must choose a valid elemental affinity");
_createWizard(ids[i], owners[i], powers[i], affinities[i]);
totalPower += powers[i];
}
// Ensure that the message includes enough eth to cover the total power of all Wizards
// If this check fails, all the Wizards that we just created will be deleted, and we'll just
// have wasted a bunch of gas. Don't be dumb, Guildmaster!
// If the guildMaster has managed to overflow totalPower, well done!
require(powerToCost(totalPower) <= msg.value, "Must pay for power in all Wizards");
// We don't return "change" if the caller overpays, because the caller is the Guildmaster and
// shouldn't be dumb like that. How many times do I have to say it? Don't be dumb, Guildmaster!
}
/// @notice Sets the affinity for a Wizard that doesn't already have its elemental affinity chosen.
/// Only usable for Exclusive Wizards (all non-Exclusives must have their affinity chosen when
/// conjured.) Even Exclusives can't change their affinity once it's been chosen.
/// @param wizardId The id of the wizard
/// @param newAffinity The new affinity of the wizard
function setAffinity(uint256 wizardId, uint8 newAffinity) external {
require(newAffinity > ELEMENT_NOTSET && newAffinity <= MAX_ELEMENT, "Must choose a valid affinity");
(address owner, , uint8 affinity) = getWizard(wizardId);
require(msg.sender == owner, "Affinity can only be set by owner");
require(affinity == ELEMENT_NOTSET, "Affinity can only be chosen once");
_wizardsById[wizardId].affinity = newAffinity;
// Tell the world this wizards now has an affinity!
emit WizardAlignmentAssigned(wizardId, newAffinity);
}
/// @dev An internal convenience function used by conjureWizard and conjureWizardMulti that takes care
/// of the work that is shared between them.
/// The use of tempElementalWizardCost and updatedElementalWizardCost deserves some explanation here.
/// Using elementalWizardCost directly would be very expensive in the case where this function is
/// called repeatedly by conjureWizardMulti. Buying an elemental wizard would update the elementalWizardCost
/// each time through this function _which would cost 5000 gas each time_. Of course, we don't actually
/// need to store the new value each time, only once at the very end. So we go through this very annoying
/// process of passing the elementalWizardCost in as an argument (tempElementalWizardCost) and returning
/// the updated value as a return value (updatedElementalWizardCost). It's enough to make one want
/// tear one's hair out. But! What's done is done, and hopefully SOMEONE will realize how much trouble
/// we went to to save them _just that little bit_ of gas cost when they decided to buy a schwack of
/// Wizards.
function _conjureWizard(
uint256 wizardId,
address owner,
uint8 affinity,
uint256 tempElementalWizardCost) private
returns (uint256 wizardCost, uint256 updatedElementalWizardCost)
{
// Check for a valid elemental affinity
require(affinity > ELEMENT_NOTSET && affinity <= MAX_ELEMENT, "Non-exclusive Wizards need a real affinity");
updatedElementalWizardCost = tempElementalWizardCost;
// Determine the price
if (affinity == ELEMENT_NEUTRAL) {
wizardCost = neutralWizardCost;
} else {
wizardCost = updatedElementalWizardCost;
// Update the elemental Wizard cost
// NOTE: This math can't overflow because the total Ether supply in wei is well less than
// 2^128. Multiplying a price in wei by some number <100k can't possibly overflow 256 bits.
updatedElementalWizardCost += (updatedElementalWizardCost * elementalWizardIncrement) / TENTH_BASIS_POINTS;
}
// Bring the new Wizard into existence!
_createWizard(wizardId, owner, costToPower(wizardCost), affinity);
}
/// @notice This is it folks, the main event! The way for the world to get new Wizards! Does
/// pretty much what it says on the box: Let's you conjure a new Wizard with a specified
/// elemental affinity. The call must include enough eth to cover the cost of the new
/// Wizard, and any excess is refunded. The power of the Wizard is derived from
/// the sale price. YOU CAN NOT PAY EXTRA TO GET MORE POWER. (But you always have the option
/// to conjure some more Wizards!) Returns the ID of the newly conjured Wizard.
/// @param affinity The elemental affinity you want for your wizard.
function conjureWizard(uint8 affinity) external payable onlyDuringSale returns (uint256 wizardId) {
wizardId = nextWizardId;
nextWizardId++;
uint256 wizardCost;
(wizardCost, elementalWizardCost) = _conjureWizard(wizardId, msg.sender, affinity, elementalWizardCost);
require(msg.value >= wizardCost, "Not enough eth to pay");
// Refund any overpayment
_transferRefund(wizardCost);
// Ensure the Wizard is being assigned to an ERC-721 aware address (either an external address,
// or a smart contract that implements onERC721Reived())
require(_checkOnERC721Received(address(0), msg.sender, wizardId, ""), "Must support erc721");
}
/// @notice A convenience function that allows you to get a whole bunch of Wizards at once! You know how
/// there's "a pride of lions", "a murder of crows", and "a parliament of owls"? Well, with this
/// here function you can conjure yourself "a stench of Cheeze Wizards"!
/// @dev This function is careful to bundle all of the external calls (the refund and onERC721Received)
/// at the end of the function to limit the risk of reentrancy attacks.
/// @param affinities the elements of the wizards
function conjureWizardMulti(uint8[] calldata affinities) external payable onlyDuringSale
returns (uint256[] memory wizardIds)
{
// allocate result array
wizardIds = new uint256[](affinities.length);
uint256 totalCost = 0;
// We take these two storage variables, and turn them into local variables for the course
// of this loop to save about 10k gas per wizard. It's kind of ugly, but that's a lot of
// gas! Won't somebody please think of the children!!
uint256 tempWizardId = nextWizardId;
uint256 tempElementalWizardCost = elementalWizardCost;
for (uint256 i = 0; i < affinities.length; i++) {
wizardIds[i] = tempWizardId;
tempWizardId++;
uint256 wizardCost;
(wizardCost, tempElementalWizardCost) = _conjureWizard(
wizardIds[i],
msg.sender,
affinities[i],
tempElementalWizardCost);
totalCost += wizardCost;
}
elementalWizardCost = tempElementalWizardCost;
nextWizardId = tempWizardId;
// check to see if there's enough eth
require(msg.value >= totalCost, "Not enough eth to pay");
// Ensure the Wizard is being assigned to an ERC-721 aware address (either an external address,
// or a smart contract that implements onERC721Received()). We unwind the logic of _checkOnERC721Received
// because called address.isContract() every time through this loop can get reasonably expensive. We do
// need to call this function for each token created, however, because it's allowed for an ERC-721 receiving
// contract to reject the transfer based on the properties of the token.
if (isContract(msg.sender)) {
for (uint256 i = 0; i < wizardIds.length; i++) {
bytes4 retval = IERC721Receiver(msg.sender).onERC721Received(msg.sender, address(0), wizardIds[i], "");
require(retval == _ERC721_RECEIVED, "Contract owner didn't accept ERC721 transfer");
}
}
// Refund any excess funds
_transferRefund(totalCost);
}
/// @dev Transfers the current balance to the owner and terminates the contract.
function destroy() external onlyGuildmaster {
selfdestruct(guildmaster);
}
}
| check to see if there's enough eth | require(msg.value >= totalCost, "Not enough eth to pay");
| 2,529,613 | [
1,
1893,
358,
2621,
309,
1915,
1807,
7304,
13750,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2583,
12,
3576,
18,
1132,
1545,
2078,
8018,
16,
315,
1248,
7304,
13750,
358,
8843,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.20;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(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));
owner = newOwner;
OwnershipTransferred(owner, newOwner);
}
}
contract CutdownTokenInterface {
//ERC20
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
//ERC677
function tokenFallback(address from, uint256 amount, bytes data) public returns (bool);
}
/**
* @title Eco Value Coin
* @dev Burnable ERC20 + ERC677 token with initial transfers blocked
*/
contract EcoValueCoin is Ownable {
using SafeMath for uint256;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed _burner, uint256 _value);
event TransfersEnabled();
event TransferRightGiven(address indexed _to);
event TransferRightCancelled(address indexed _from);
event WithdrawnERC20Tokens(address indexed _tokenContract, address indexed _owner, uint256 _balance);
event WithdrawnEther(address indexed _owner, uint256 _balance);
string public constant name = "Eco Value Coin";
string public constant symbol = "EVC";
uint256 public constant decimals = 18;
uint256 public constant initialSupply = 3300000000 * (10 ** decimals);
uint256 public totalSupply;
mapping(address => uint256) public balances;
mapping(address => mapping (address => uint256)) internal allowed;
//This mapping is used for the token owner and crowdsale contract to
//transfer tokens before they are transferable
mapping(address => bool) public transferGrants;
//This flag controls the global token transfer
bool public transferable;
/**
* @dev Modifier to check if tokens can be transfered.
*/
modifier canTransfer() {
require(transferable || transferGrants[msg.sender]);
_;
}
/**
* @dev The constructor sets the original `owner` of the contract
* to the sender account and assigns them all tokens.
*/
function EcoValueCoin() public {
owner = msg.sender;
totalSupply = initialSupply;
balances[owner] = totalSupply;
transferGrants[owner] = true;
}
/**
* @dev This contract does not accept any ether.
* Any forced ether can be withdrawn with `withdrawEther()` by the owner.
*/
function () payable public {
revert();
}
/**
* @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 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) canTransfer public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev 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) canTransfer public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) canTransfer public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) canTransfer public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) canTransfer public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) canTransfer public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
/**
* @dev Enables the transfer of tokens for everyone
*/
function enableTransfers() onlyOwner public {
require(!transferable);
transferable = true;
TransfersEnabled();
}
/**
* @dev Assigns the special transfer right, before transfers are enabled
* @param _to The address receiving the transfer grant
*/
function grantTransferRight(address _to) onlyOwner public {
require(!transferable);
require(!transferGrants[_to]);
require(_to != address(0));
transferGrants[_to] = true;
TransferRightGiven(_to);
}
/**
* @dev Removes the special transfer right, before transfers are enabled
* @param _from The address that the transfer grant is removed from
*/
function cancelTransferRight(address _from) onlyOwner public {
require(!transferable);
require(transferGrants[_from]);
transferGrants[_from] = false;
TransferRightCancelled(_from);
}
/**
* @dev Allows to transfer out the balance of arbitrary ERC20 tokens from the contract.
* @param _tokenContract The contract address of the ERC20 token.
*/
function withdrawERC20Tokens(address _tokenContract) onlyOwner public {
CutdownTokenInterface token = CutdownTokenInterface(_tokenContract);
uint256 totalBalance = token.balanceOf(address(this));
token.transfer(owner, totalBalance);
WithdrawnERC20Tokens(_tokenContract, owner, totalBalance);
}
/**
* @dev Allows to transfer out the ether balance that was forced into this contract, e.g with `selfdestruct`
*/
function withdrawEther() public onlyOwner {
uint256 totalBalance = this.balance;
require(totalBalance > 0);
owner.transfer(totalBalance);
WithdrawnEther(owner, totalBalance);
}
} | * @dev Assigns the special transfer right, before transfers are enabled @param _to The address receiving the transfer grant/ | function grantTransferRight(address _to) onlyOwner public {
require(!transferable);
require(!transferGrants[_to]);
require(_to != address(0));
transferGrants[_to] = true;
TransferRightGiven(_to);
}
| 57,637 | [
1,
24842,
326,
4582,
7412,
2145,
16,
1865,
29375,
854,
3696,
225,
389,
869,
1021,
1758,
15847,
326,
7412,
7936,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
7936,
5912,
4726,
12,
2867,
389,
869,
13,
1338,
5541,
1071,
288,
203,
565,
2583,
12,
5,
13866,
429,
1769,
203,
565,
2583,
12,
5,
13866,
29598,
63,
67,
869,
19226,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
7412,
29598,
63,
67,
869,
65,
273,
638,
31,
203,
565,
12279,
4726,
6083,
24899,
869,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/100/0x0Ac7ac8C6Eb5BbBEbE2d02E6B6f5B2B8e05759f1/sources/contracts/LP.sol | * @notice Throw if caller have no access to function with selector `selector`./ | modifier restricted(bytes4 selector) {
checkAccess(msg.sender, address(this), selector);
_;
}
| 14,285,399 | [
1,
8282,
309,
4894,
1240,
1158,
2006,
358,
445,
598,
3451,
1375,
9663,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
15693,
12,
3890,
24,
3451,
13,
288,
203,
3639,
28484,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3451,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./interfaces/IAuthorizer.sol";
import "./interfaces/IWETH.sol";
import "./VaultAuthorization.sol";
import "./FlashLoans.sol";
import "./Swaps.sol";
/**
* @dev The `Vault` is Balancer V2's core contract. A single instance of it exists for the entire network, and it is the
* entity used to interact with Pools by Liquidity Providers who join and exit them, Traders who swap, and Asset
* Managers who withdraw and deposit tokens.
*
* The `Vault`'s source code is split among a number of sub-contracts, with the goal of improving readability and making
* understanding the system easier. Most sub-contracts have been marked as `abstract` to explicitly indicate that only
* the full `Vault` is meant to be deployed.
*
* Roughly speaking, these are the contents of each sub-contract:
*
* - `AssetManagers`: Pool token Asset Manager registry, and Asset Manager interactions.
* - `Fees`: set and compute protocol fees.
* - `FlashLoans`: flash loan transfers and fees.
* - `PoolBalances`: Pool joins and exits.
* - `PoolRegistry`: Pool registration, ID management, and basic queries.
* - `PoolTokens`: Pool token registration and registration, and balance queries.
* - `Swaps`: Pool swaps.
* - `UserBalance`: manage user balances (Internal Balance operations and external balance transfers)
* - `VaultAuthorization`: access control, relayers and signature validation.
*
* Additionally, the different Pool specializations are handled by the `GeneralPoolsBalance`,
* `MinimalSwapInfoPoolsBalance` and `TwoTokenPoolsBalance` sub-contracts, which in turn make use of the
* `BalanceAllocation` library.
*
* The most important goal of the `Vault` is to make token swaps use as little gas as possible. This is reflected in a
* multitude of design decisions, from minor things like the format used to store Pool IDs, to major features such as
* the different Pool specialization settings.
*
* Finally, the large number of tasks carried out by the Vault means its bytecode is very large, close to exceeding
* the contract size limit imposed by EIP 170 (https://eips.ethereum.org/EIPS/eip-170). Manual tuning of the source code
* was required to improve code generation and bring the bytecode size below this limit. This includes extensive
* utilization of `internal` functions (particularly inside modifiers), usage of named return arguments, dedicated
* storage access methods, dynamic revert reason generation, and usage of inline assembly, to name a few.
*/
contract Vault is VaultAuthorization, FlashLoans, Swaps {
constructor(
IAuthorizer authorizer,
IWETH weth,
uint256 pauseWindowDuration,
uint256 bufferPeriodDuration
) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) {
// solhint-disable-previous-line no-empty-blocks
}
function setPaused(bool paused) external override nonReentrant authenticate {
_setPaused(paused);
}
// solhint-disable-next-line func-name-mixedcase
function WETH() external view override returns (IWETH) {
return _WETH();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/openzeppelin/IERC20.sol";
/**
* @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support
* sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals.
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/helpers/TemporarilyPausable.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/SignaturesValidator.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev Manages access control of Vault permissioned functions by relying on the Authorizer and signature validation.
*
* Additionally handles relayer access and approval.
*/
abstract contract VaultAuthorization is
IVault,
ReentrancyGuard,
Authentication,
SignaturesValidator,
TemporarilyPausable
{
// Ideally, we'd store the type hashes as immutable state variables to avoid computing the hash at runtime, but
// unfortunately immutable variables cannot be used in assembly, so we just keep the precomputed hashes instead.
// _JOIN_TYPE_HASH = keccak256("JoinPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _JOIN_TYPE_HASH = 0x3f7b71252bd19113ff48c19c6e004a9bcfcca320a0d74d58e85877cbd7dcae58;
// _EXIT_TYPE_HASH = keccak256("ExitPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _EXIT_TYPE_HASH = 0x8bbc57f66ea936902f50a71ce12b92c43f3c5340bb40c27c4e90ab84eeae3353;
// _SWAP_TYPE_HASH = keccak256("Swap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe;
// _BATCH_SWAP_TYPE_HASH = keccak256("BatchSwap(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32 private constant _BATCH_SWAP_TYPE_HASH = 0x9bfc43a4d98313c6766986ffd7c916c7481566d9f224c6819af0a53388aced3a;
// _SET_RELAYER_TYPE_HASH =
// keccak256("SetRelayerApproval(bytes calldata,address sender,uint256 nonce,uint256 deadline)");
bytes32
private constant _SET_RELAYER_TYPE_HASH = 0xa3f865aa351e51cfeb40f5178d1564bb629fe9030b83caf6361d1baaf5b90b5a;
IAuthorizer private _authorizer;
mapping(address => mapping(address => bool)) private _approvedRelayers;
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call this function (that
* is, it is a relayer for that function), and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*
* Should only be applied to external functions.
*/
modifier authenticateFor(address user) {
_authenticateFor(user);
_;
}
constructor(IAuthorizer authorizer)
// The Vault is a singleton, so it simply uses its own address to disambiguate action identifiers.
Authentication(bytes32(uint256(address(this))))
SignaturesValidator("Balancer V2 Vault")
{
_setAuthorizer(authorizer);
}
function setAuthorizer(IAuthorizer newAuthorizer) external override nonReentrant authenticate {
_setAuthorizer(newAuthorizer);
}
function _setAuthorizer(IAuthorizer newAuthorizer) private {
emit AuthorizerChanged(newAuthorizer);
_authorizer = newAuthorizer;
}
function getAuthorizer() external view override returns (IAuthorizer) {
return _authorizer;
}
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external override nonReentrant whenNotPaused authenticateFor(sender) {
_approvedRelayers[sender][relayer] = approved;
emit RelayerApprovalChanged(relayer, sender, approved);
}
function hasApprovedRelayer(address user, address relayer) external view override returns (bool) {
return _hasApprovedRelayer(user, relayer);
}
/**
* @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call the entry point
* function (that is, it is a relayer for that function) and either:
* a) `user` approved the caller as a relayer (via `setRelayerApproval`), or
* b) a valid signature from them was appended to the calldata.
*/
function _authenticateFor(address user) internal {
if (msg.sender != user) {
// In this context, 'permission to call a function' means 'being a relayer for a function'.
_authenticateCaller();
// Being a relayer is not sufficient: `user` must have also approved the caller either via
// `setRelayerApproval`, or by providing a signature appended to the calldata.
if (!_hasApprovedRelayer(user, msg.sender)) {
_validateSignature(user, Errors.USER_DOESNT_ALLOW_RELAYER);
}
}
}
/**
* @dev Returns true if `user` approved `relayer` to act as a relayer for them.
*/
function _hasApprovedRelayer(address user, address relayer) internal view returns (bool) {
return _approvedRelayers[user][relayer];
}
function _canPerform(bytes32 actionId, address user) internal view override returns (bool) {
// Access control is delegated to the Authorizer.
return _authorizer.canPerform(actionId, user, address(this));
}
function _typeHash() internal pure override returns (bytes32 hash) {
// This is a simple switch-case statement, trivially written in Solidity by chaining else-if statements, but the
// assembly implementation results in much denser bytecode.
// solhint-disable-next-line no-inline-assembly
assembly {
// The function selector is located at the first 4 bytes of calldata. We copy the first full calldata
// 256 word, and then perform a logical shift to the right, moving the selector to the least significant
// 4 bytes.
let selector := shr(224, calldataload(0))
// With the selector in the least significant 4 bytes, we can use 4 byte literals with leading zeros,
// resulting in dense bytecode (PUSH4 opcodes).
switch selector
case 0xb95cac28 {
hash := _JOIN_TYPE_HASH
}
case 0x8bdb3913 {
hash := _EXIT_TYPE_HASH
}
case 0x52bbbe29 {
hash := _SWAP_TYPE_HASH
}
case 0x945bcec9 {
hash := _BATCH_SWAP_TYPE_HASH
}
case 0xfa6e671d {
hash := _SET_RELAYER_TYPE_HASH
}
default {
hash := 0x0000000000000000000000000000000000000000000000000000000000000000
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// This flash loan provider was based on the Aave protocol's open source
// implementation and terminology and interfaces are intentionally kept
// similar
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./interfaces/IFlashLoanRecipient.sol";
/**
* @dev Handles Flash Loans through the Vault. Calls the `receiveFlashLoan` hook on the flash loan recipient
* contract, which implements the `IFlashLoanRecipient` interface.
*/
abstract contract FlashLoans is Fees, ReentrancyGuard, TemporarilyPausable {
using SafeERC20 for IERC20;
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external override nonReentrant whenNotPaused {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
uint256[] memory feeAmounts = new uint256[](tokens.length);
uint256[] memory preLoanBalances = new uint256[](tokens.length);
// Used to ensure `tokens` is sorted in ascending order, which ensures token uniqueness.
IERC20 previousToken = IERC20(0);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
_require(token > previousToken, token == IERC20(0) ? Errors.ZERO_TOKEN : Errors.UNSORTED_TOKENS);
previousToken = token;
preLoanBalances[i] = token.balanceOf(address(this));
feeAmounts[i] = _calculateFlashLoanFeeAmount(amount);
_require(preLoanBalances[i] >= amount, Errors.INSUFFICIENT_FLASH_LOAN_BALANCE);
token.safeTransfer(address(recipient), amount);
}
recipient.receiveFlashLoan(tokens, amounts, feeAmounts, userData);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 preLoanBalance = preLoanBalances[i];
// Checking for loan repayment first (without accounting for fees) makes for simpler debugging, and results
// in more accurate revert reasons if the flash loan protocol fee percentage is zero.
uint256 postLoanBalance = token.balanceOf(address(this));
_require(postLoanBalance >= preLoanBalance, Errors.INVALID_POST_LOAN_BALANCE);
// No need for checked arithmetic since we know the loan was fully repaid.
uint256 receivedFeeAmount = postLoanBalance - preLoanBalance;
_require(receivedFeeAmount >= feeAmounts[i], Errors.INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT);
_payFeeAmount(token, receivedFeeAmount);
emit FlashLoan(recipient, token, amounts[i], receivedFeeAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/EnumerableMap.sol";
import "../lib/openzeppelin/EnumerableSet.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./PoolBalances.sol";
import "./interfaces/IPoolSwapStructs.sol";
import "./interfaces/IGeneralPool.sol";
import "./interfaces/IMinimalSwapInfoPool.sol";
import "./balances/BalanceAllocation.sol";
/**
* Implements the Vault's high-level swap functionality.
*
* Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. They need not trust the Pool
* contracts to do this: all security checks are made by the Vault.
*
* The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
* In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
* and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
* More complex swaps, such as one 'token in' to multiple tokens out can be achieved by batching together
* individual swaps.
*/
abstract contract Swaps is ReentrancyGuard, PoolBalances {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
using Math for int256;
using Math for uint256;
using SafeCast for uint256;
using BalanceAllocation for bytes32;
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (uint256 amountCalculated)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
// This revert reason is for consistency with `batchSwap`: an equivalent `swap` performed using that function
// would result in this error.
_require(singleSwap.amount > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
IERC20 tokenIn = _translateToIERC20(singleSwap.assetIn);
IERC20 tokenOut = _translateToIERC20(singleSwap.assetOut);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Initializing each struct field one-by-one uses less gas than setting all at once.
IPoolSwapStructs.SwapRequest memory poolRequest;
poolRequest.poolId = singleSwap.poolId;
poolRequest.kind = singleSwap.kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = singleSwap.amount;
poolRequest.userData = singleSwap.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized.
uint256 amountIn;
uint256 amountOut;
(amountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
_require(singleSwap.kind == SwapKind.GIVEN_IN ? amountOut >= limit : amountIn <= limit, Errors.SWAP_LIMIT);
_receiveAsset(singleSwap.assetIn, amountIn, funds.sender, funds.fromInternalBalance);
_sendAsset(singleSwap.assetOut, amountOut, funds.recipient, funds.toInternalBalance);
// If the asset in is ETH, then `amountIn` ETH was wrapped into WETH.
_handleRemainingEth(_isETH(singleSwap.assetIn) ? amountIn : 0);
}
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
)
external
payable
override
nonReentrant
whenNotPaused
authenticateFor(funds.sender)
returns (int256[] memory assetDeltas)
{
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
_require(block.timestamp <= deadline, Errors.SWAP_DEADLINE);
InputHelpers.ensureInputLengthMatch(assets.length, limits.length);
// Perform the swaps, updating the Pool token balances and computing the net Vault asset deltas.
assetDeltas = _swapWithPools(swaps, assets, funds, kind);
// Process asset deltas, by either transferring assets from the sender (for positive deltas) or to the recipient
// (for negative deltas).
uint256 wrappedEth = 0;
for (uint256 i = 0; i < assets.length; ++i) {
IAsset asset = assets[i];
int256 delta = assetDeltas[i];
_require(delta <= limits[i], Errors.SWAP_LIMIT);
if (delta > 0) {
uint256 toReceive = uint256(delta);
_receiveAsset(asset, toReceive, funds.sender, funds.fromInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(toReceive);
}
} else if (delta < 0) {
uint256 toSend = uint256(-delta);
_sendAsset(asset, toSend, funds.recipient, funds.toInternalBalance);
}
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
// For `_swapWithPools` to handle both 'given in' and 'given out' swaps, it internally tracks the 'given' amount
// (supplied by the caller), and the 'calculated' amount (returned by the Pool in response to the swap request).
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'given' token (the token whose
* amount is supplied by the caller).
*/
function _tokenGiven(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenIn : tokenOut;
}
/**
* @dev Given the two swap tokens and the swap kind, returns which one is the 'calculated' token (the token whose
* amount is calculated by the Pool).
*/
function _tokenCalculated(
SwapKind kind,
IERC20 tokenIn,
IERC20 tokenOut
) private pure returns (IERC20) {
return kind == SwapKind.GIVEN_IN ? tokenOut : tokenIn;
}
/**
* @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind.
*/
function _getAmounts(
SwapKind kind,
uint256 amountGiven,
uint256 amountCalculated
) private pure returns (uint256 amountIn, uint256 amountOut) {
if (kind == SwapKind.GIVEN_IN) {
(amountIn, amountOut) = (amountGiven, amountCalculated);
} else {
// SwapKind.GIVEN_OUT
(amountIn, amountOut) = (amountCalculated, amountGiven);
}
}
/**
* @dev Performs all `swaps`, calling swap hooks on the Pool contracts and updating their balances. Does not cause
* any transfer of tokens - instead it returns the net Vault token deltas: positive if the Vault should receive
* tokens, and negative if it should send them.
*/
function _swapWithPools(
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
SwapKind kind
) private returns (int256[] memory assetDeltas) {
assetDeltas = new int256[](assets.length);
// These variables could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
BatchSwapStep memory batchSwapStep;
IPoolSwapStructs.SwapRequest memory poolRequest;
// These store data about the previous swap here to implement multihop logic across swaps.
IERC20 previousTokenCalculated;
uint256 previousAmountCalculated;
for (uint256 i = 0; i < swaps.length; ++i) {
batchSwapStep = swaps[i];
bool withinBounds = batchSwapStep.assetInIndex < assets.length &&
batchSwapStep.assetOutIndex < assets.length;
_require(withinBounds, Errors.OUT_OF_BOUNDS);
IERC20 tokenIn = _translateToIERC20(assets[batchSwapStep.assetInIndex]);
IERC20 tokenOut = _translateToIERC20(assets[batchSwapStep.assetOutIndex]);
_require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN);
// Sentinel value for multihop logic
if (batchSwapStep.amount == 0) {
// When the amount given is zero, we use the calculated amount for the previous swap, as long as the
// current swap's given token is the previous calculated token. This makes it possible to swap a
// given amount of token A for token B, and then use the resulting token B amount to swap for token C.
_require(i > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP);
bool usingPreviousToken = previousTokenCalculated == _tokenGiven(kind, tokenIn, tokenOut);
_require(usingPreviousToken, Errors.MALCONSTRUCTED_MULTIHOP_SWAP);
batchSwapStep.amount = previousAmountCalculated;
}
// Initializing each struct field one-by-one uses less gas than setting all at once
poolRequest.poolId = batchSwapStep.poolId;
poolRequest.kind = kind;
poolRequest.tokenIn = tokenIn;
poolRequest.tokenOut = tokenOut;
poolRequest.amount = batchSwapStep.amount;
poolRequest.userData = batchSwapStep.userData;
poolRequest.from = funds.sender;
poolRequest.to = funds.recipient;
// The lastChangeBlock field is left uninitialized
uint256 amountIn;
uint256 amountOut;
(previousAmountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest);
previousTokenCalculated = _tokenCalculated(kind, tokenIn, tokenOut);
// Accumulate Vault deltas across swaps
assetDeltas[batchSwapStep.assetInIndex] = assetDeltas[batchSwapStep.assetInIndex].add(amountIn.toInt256());
assetDeltas[batchSwapStep.assetOutIndex] = assetDeltas[batchSwapStep.assetOutIndex].sub(
amountOut.toInt256()
);
}
}
/**
* @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and
* updating the Pool's balance.
*
* Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind.
*/
function _swapWithPool(IPoolSwapStructs.SwapRequest memory request)
private
returns (
uint256 amountCalculated,
uint256 amountIn,
uint256 amountOut
)
{
// Get the calculated amount from the Pool and update its balances
address pool = _getPoolAddress(request.poolId);
PoolSpecialization specialization = _getPoolSpecialization(request.poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else {
// PoolSpecialization.GENERAL
amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool));
}
(amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut);
}
function _processTwoTokenPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool)
private
returns (uint256 amountCalculated)
{
// For gas efficiency reasons, this function uses low-level knowledge of how Two Token Pool balances are
// stored internally, instead of using getters and setters for all operations.
(
bytes32 tokenABalance,
bytes32 tokenBBalance,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(request.poolId, request.tokenIn, request.tokenOut);
// We have the two Pool balances, but we don't know which one is 'token in' or 'token out'.
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// In Two Token Pools, token A has a smaller address than token B
if (request.tokenIn < request.tokenOut) {
// in is A, out is B
tokenInBalance = tokenABalance;
tokenOutBalance = tokenBBalance;
} else {
// in is B, out is A
tokenOutBalance = tokenABalance;
tokenInBalance = tokenBBalance;
}
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
// We check the token ordering again to create the new shared cash packed struct
poolBalances.sharedCash = request.tokenIn < request.tokenOut
? BalanceAllocation.toSharedCash(tokenInBalance, tokenOutBalance) // in is A, out is B
: BalanceAllocation.toSharedCash(tokenOutBalance, tokenInBalance); // in is B, out is A
}
function _processMinimalSwapInfoPoolSwapRequest(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool
) private returns (uint256 amountCalculated) {
bytes32 tokenInBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenIn);
bytes32 tokenOutBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenOut);
// Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap
(tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook(
request,
pool,
tokenInBalance,
tokenOutBalance
);
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenIn] = tokenInBalance;
_minimalSwapInfoPoolsBalances[request.poolId][request.tokenOut] = tokenOutBalance;
}
/**
* @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token
* Pools do this.
*/
function _callMinimalSwapInfoPoolOnSwapHook(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool,
bytes32 tokenInBalance,
bytes32 tokenOutBalance
)
internal
returns (
bytes32 newTokenInBalance,
bytes32 newTokenOutBalance,
uint256 amountCalculated
)
{
uint256 tokenInTotal = tokenInBalance.total();
uint256 tokenOutTotal = tokenOutBalance.total();
request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock());
// Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
newTokenInBalance = tokenInBalance.increaseCash(amountIn);
newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
}
function _processGeneralPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IGeneralPool pool)
private
returns (uint256 amountCalculated)
{
bytes32 tokenInBalance;
bytes32 tokenOutBalance;
// We access both token indexes without checking existence, because we will do it manually immediately after.
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[request.poolId];
uint256 indexIn = poolBalances.unchecked_indexOf(request.tokenIn);
uint256 indexOut = poolBalances.unchecked_indexOf(request.tokenOut);
if (indexIn == 0 || indexOut == 0) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(request.poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
// EnumerableMap stores indices *plus one* to use the zero index as a sentinel value - because these are valid,
// we can undo this.
indexIn -= 1;
indexOut -= 1;
uint256 tokenAmount = poolBalances.length();
uint256[] memory currentBalances = new uint256[](tokenAmount);
request.lastChangeBlock = 0;
for (uint256 i = 0; i < tokenAmount; i++) {
// Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we
// know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads.
bytes32 balance = poolBalances.unchecked_valueAt(i);
currentBalances[i] = balance.total();
request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock());
if (i == indexIn) {
tokenInBalance = balance;
} else if (i == indexOut) {
tokenOutBalance = balance;
}
}
// Perform the swap request callback and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, currentBalances, indexIn, indexOut);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
tokenInBalance = tokenInBalance.increaseCash(amountIn);
tokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
// Because no tokens were registered or deregistered between now or when we retrieved the indexes for
// 'token in' and 'token out', we can use `unchecked_setAt` to save storage reads.
poolBalances.unchecked_setAt(indexIn, tokenInBalance);
poolBalances.unchecked_setAt(indexOut, tokenOutBalance);
}
// This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external override returns (int256[] memory) {
// In order to accurately 'simulate' swaps, this function actually does perform the swaps, including calling the
// Pool hooks and updating balances in storage. However, once it computes the final Vault Deltas, it
// reverts unconditionally, returning this array as the revert data.
//
// By wrapping this reverting call, we can decode the deltas 'returned' and return them as a normal Solidity
// function would. The only caveat is the function becomes non-view, but off-chain clients can still call it
// via eth_call to get the expected result.
//
// This technique was inspired by the work from the Gnosis team in the Gnosis Safe contract:
// https://github.com/gnosis/safe-contracts/blob/v1.2.0/contracts/GnosisSafe.sol#L265
//
// Most of this function is implemented using inline assembly, as the actual work it needs to do is not
// significant, and Solidity is not particularly well-suited to generate this behavior, resulting in a large
// amount of generated bytecode.
if (msg.sender != address(this)) {
// We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of
// the preceding if statement will be executed instead.
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(msg.data);
// solhint-disable-next-line no-inline-assembly
assembly {
// This call should always revert to decode the actual asset deltas from the revert reason
switch success
case 0 {
// Note we are manually writing the memory slot 0. We can safely overwrite whatever is
// stored there as we take full control of the execution and then immediately return.
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise
// there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04)
let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
// If the first 4 bytes don't match with the expected signature, we forward the revert reason.
if eq(eq(error, 0xfa61cc1200000000000000000000000000000000000000000000000000000000), 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
// The returndata contains the signature, followed by the raw memory representation of an array:
// length + data. We need to return an ABI-encoded representation of this array.
// An ABI-encoded array contains an additional field when compared to its raw memory
// representation: an offset to the location of the length. The offset itself is 32 bytes long,
// so the smallest value we can use is 32 for the data to be located immediately after it.
mstore(0, 32)
// We now copy the raw memory array from returndata into memory. Since the offset takes up 32
// bytes, we start copying at address 0x20. We also get rid of the error signature, which takes
// the first four bytes of returndata.
let size := sub(returndatasize(), 0x04)
returndatacopy(0x20, 0x04, size)
// We finally return the ABI-encoded array, which has a total length equal to that of the array
// (returndata), plus the 32 bytes for the offset.
return(0, add(size, 32))
}
default {
// This call should always revert, but we fail nonetheless if that didn't happen
invalid()
}
}
} else {
int256[] memory deltas = _swapWithPools(swaps, assets, funds, kind);
// solhint-disable-next-line no-inline-assembly
assembly {
// We will return a raw representation of the array in memory, which is composed of a 32 byte length,
// followed by the 32 byte int256 values. Because revert expects a size in bytes, we multiply the array
// length (stored at `deltas`) by 32.
let size := mul(mload(deltas), 32)
// We send one extra value for the error signature "QueryError(int256[])" which is 0xfa61cc12.
// We store it in the previous slot to the `deltas` array. We know there will be at least one available
// slot due to how the memory scratch space works.
// We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
mstore(sub(deltas, 0x20), 0x00000000000000000000000000000000000000000000000000000000fa61cc12)
let start := sub(deltas, 0x04)
// When copying from `deltas` into returndata, we copy an additional 36 bytes to also return the array's
// length and the error signature.
revert(start, add(size, 36))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./IAuthentication.sol";
/**
* @dev Building block for performing access control on external functions.
*
* This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied
* to external functions to only make them callable by authorized accounts.
*
* Derived contracts must implement the `_canPerform` function, which holds the actual access control logic.
*/
abstract contract Authentication is IAuthentication {
bytes32 private immutable _actionIdDisambiguator;
/**
* @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in
* multi contract systems.
*
* There are two main uses for it:
* - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers
* unique. The contract's own address is a good option.
* - if the contract belongs to a family that shares action identifiers for the same functions, an identifier
* shared by the entire family (and no other contract) should be used instead.
*/
constructor(bytes32 actionIdDisambiguator) {
_actionIdDisambiguator = actionIdDisambiguator;
}
/**
* @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions.
*/
modifier authenticate() {
_authenticateCaller();
_;
}
/**
* @dev Reverts unless the caller is allowed to call the entry point function.
*/
function _authenticateCaller() internal view {
bytes32 actionId = getActionId(msg.sig);
_require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED);
}
function getActionId(bytes4 selector) public view override returns (bytes32) {
// Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the
// function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of
// multiple contracts.
return keccak256(abi.encodePacked(_actionIdDisambiguator, selector));
}
function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ITemporarilyPausable.sol";
/**
* @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be
* used as an emergency switch in case a security vulnerability or threat is identified.
*
* The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be
* unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets
* system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful
* analysis later determines there was a false alarm.
*
* If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional
* Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time
* to react to an emergency, even if the threat is discovered shortly before the Pause Window expires.
*
* Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is
* irreversible.
*/
abstract contract TemporarilyPausable is ITemporarilyPausable {
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days;
uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days;
uint256 private immutable _pauseWindowEndTime;
uint256 private immutable _bufferPeriodEndTime;
bool private _paused;
constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) {
_require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION);
_require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION);
uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration;
_pauseWindowEndTime = pauseWindowEndTime;
_bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration;
}
/**
* @dev Reverts if the contract is paused.
*/
modifier whenNotPaused() {
_ensureNotPaused();
_;
}
/**
* @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer
* Period.
*/
function getPausedState()
external
view
override
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
)
{
paused = !_isNotPaused();
pauseWindowEndTime = _getPauseWindowEndTime();
bufferPeriodEndTime = _getBufferPeriodEndTime();
}
/**
* @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and
* unpaused until the end of the Buffer Period.
*
* Once the Buffer Period expires, this function reverts unconditionally.
*/
function _setPaused(bool paused) internal {
if (paused) {
_require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED);
} else {
_require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED);
}
_paused = paused;
emit PausedStateChanged(paused);
}
/**
* @dev Reverts if the contract is paused.
*/
function _ensureNotPaused() internal view {
_require(_isNotPaused(), Errors.PAUSED);
}
/**
* @dev Returns true if the contract is unpaused.
*
* Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no
* longer accessed.
*/
function _isNotPaused() internal view returns (bool) {
// After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access.
return block.timestamp > _getBufferPeriodEndTime() || !_paused;
}
// These getters lead to reduced bytecode size by inlining the immutable variables in a single place.
function _getPauseWindowEndTime() private view returns (uint256) {
return _pauseWindowEndTime;
}
function _getBufferPeriodEndTime() private view returns (uint256) {
return _bufferPeriodEndTime;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./BalancerErrors.sol";
import "./ISignaturesValidator.sol";
import "../openzeppelin/EIP712.sol";
/**
* @dev Utility for signing Solidity function calls.
*
* This contract relies on the fact that Solidity contracts can be called with extra calldata, and enables
* meta-transaction schemes by appending an EIP712 signature of the original calldata at the end.
*
* Derived contracts must implement the `_typeHash` function to map function selectors to EIP712 structs.
*/
abstract contract SignaturesValidator is ISignaturesValidator, EIP712 {
// The appended data consists of a deadline, plus the [v,r,s] signature. For simplicity, we use a full 256 bit slot
// for each of these values, even if 'v' is typically an 8 bit value.
uint256 internal constant _EXTRA_CALLDATA_LENGTH = 4 * 32;
// Replay attack prevention for each user.
mapping(address => uint256) internal _nextNonce;
constructor(string memory name) EIP712(name, "1") {
// solhint-disable-previous-line no-empty-blocks
}
function getDomainSeparator() external view override returns (bytes32) {
return _domainSeparatorV4();
}
function getNextNonce(address user) external view override returns (uint256) {
return _nextNonce[user];
}
/**
* @dev Reverts with `errorCode` unless a valid signature for `user` was appended to the calldata.
*/
function _validateSignature(address user, uint256 errorCode) internal {
uint256 nextNonce = _nextNonce[user]++;
_require(_isSignatureValid(user, nextNonce), errorCode);
}
function _isSignatureValid(address user, uint256 nonce) private view returns (bool) {
uint256 deadline = _deadline();
// The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy.
// solhint-disable-next-line not-rely-on-time
if (deadline < block.timestamp) {
return false;
}
bytes32 typeHash = _typeHash();
if (typeHash == bytes32(0)) {
// Prevent accidental signature validation for functions that don't have an associated type hash.
return false;
}
// All type hashes have this format: (bytes calldata, address sender, uint256 nonce, uint256 deadline).
bytes32 structHash = keccak256(abi.encode(typeHash, keccak256(_calldata()), msg.sender, nonce, deadline));
bytes32 digest = _hashTypedDataV4(structHash);
(uint8 v, bytes32 r, bytes32 s) = _signature();
address recoveredAddress = ecrecover(digest, v, r, s);
// ecrecover returns the zero address on recover failure, so we need to handle that explicitly.
return recoveredAddress != address(0) && recoveredAddress == user;
}
/**
* @dev Returns the EIP712 type hash for the current entry point function, which can be identified by its function
* selector (available as `msg.sig`).
*
* The type hash must conform to the following format:
* <name>(bytes calldata, address sender, uint256 nonce, uint256 deadline)
*
* If 0x00, all signatures will be considered invalid.
*/
function _typeHash() internal view virtual returns (bytes32);
/**
* @dev Extracts the signature deadline from extra calldata.
*
* This function returns bogus data if no signature is included.
*/
function _deadline() internal pure returns (uint256) {
// The deadline is the first extra argument at the end of the original calldata.
return uint256(_decodeExtraCalldataWord(0));
}
/**
* @dev Extracts the signature parameters from extra calldata.
*
* This function returns bogus data if no signature is included. This is not a security risk, as that data would not
* be considered a valid signature in the first place.
*/
function _signature()
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// v, r and s are appended after the signature deadline, in that order.
v = uint8(uint256(_decodeExtraCalldataWord(0x20)));
r = _decodeExtraCalldataWord(0x40);
s = _decodeExtraCalldataWord(0x60);
}
/**
* @dev Returns the original calldata, without the extra bytes containing the signature.
*
* This function returns bogus data if no signature is included.
*/
function _calldata() internal pure returns (bytes memory result) {
result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents.
if (result.length > _EXTRA_CALLDATA_LENGTH) {
// solhint-disable-next-line no-inline-assembly
assembly {
// We simply overwrite the array length with the reduced one.
mstore(result, sub(calldatasize(), _EXTRA_CALLDATA_LENGTH))
}
}
}
/**
* @dev Returns a 256 bit word from 'extra' calldata, at some offset from the expected end of the original calldata.
*
* This function returns bogus data if no signature is included.
*/
function _decodeExtraCalldataWord(uint256 offset) private pure returns (bytes32 result) {
// solhint-disable-next-line no-inline-assembly
assembly {
result := calldataload(add(sub(calldatasize(), _EXTRA_CALLDATA_LENGTH), offset))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the ReentrancyGuard library from OpenZeppelin contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs but reduced bytecode size.
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// 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: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "../ProtocolFeesCollector.sol";
import "../../lib/helpers/ISignaturesValidator.sol";
import "../../lib/helpers/ITemporarilyPausable.sol";
pragma solidity ^0.7.0;
/**
* @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
* don't override one of these declarations.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// Generalities about the Vault:
//
// - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
// transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
// `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
// calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
// a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
//
// - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
// while execution control is transferred to a token contract during a swap) will result in a revert. View
// functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
// Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
//
// - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.
// Authorizer
//
// Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
// outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
// can perform a given action.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// Relayers
//
// Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
// Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
// and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
// this power, two things must occur:
// - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
// means that Balancer governance must approve each individual contract to act as a relayer for the intended
// functions.
// - Each user must approve the relayer to act on their behalf.
// This double protection means users cannot be tricked into approving malicious relayers (because they will not
// have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
// Authorizer or governance drain user funds, since they would also need to be approved by each individual user.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (ProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
interface IAuthentication {
/**
* @dev Returns the action identifier associated with the external function described by `selector`.
*/
function getActionId(bytes4 selector) external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
// Silence state mutability warning without generating bytecode.
// See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
// https://github.com/ethereum/solidity/issues/2691
this;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "../../lib/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/helpers/Authentication.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IAuthorizer.sol";
/**
* @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the
* Vault performs to reduce its overall bytecode size.
*
* The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are
* sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated
* to the Vault's own authorizer.
*/
contract ProtocolFeesCollector is Authentication, ReentrancyGuard {
using SafeERC20 for IERC20;
// Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%).
uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50%
uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1%
IVault public immutable vault;
// All fee percentages are 18-decimal fixed point numbers.
// The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not
// actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due
// when users join and exit them.
uint256 private _swapFeePercentage;
// The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent.
uint256 private _flashLoanFeePercentage;
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
constructor(IVault _vault)
// The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action
// identifiers.
Authentication(bytes32(uint256(address(this))))
{
vault = _vault;
}
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external nonReentrant authenticate {
InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length);
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
uint256 amount = amounts[i];
token.safeTransfer(recipient, amount);
}
}
function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate {
_require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH);
_swapFeePercentage = newSwapFeePercentage;
emit SwapFeePercentageChanged(newSwapFeePercentage);
}
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate {
_require(
newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE,
Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH
);
_flashLoanFeePercentage = newFlashLoanFeePercentage;
emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage);
}
function getSwapFeePercentage() external view returns (uint256) {
return _swapFeePercentage;
}
function getFlashLoanFeePercentage() external view returns (uint256) {
return _flashLoanFeePercentage;
}
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) {
feeAmounts = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
feeAmounts[i] = tokens[i].balanceOf(address(this));
}
}
function getAuthorizer() external view returns (IAuthorizer) {
return _getAuthorizer();
}
function _canPerform(bytes32 actionId, address account) internal view override returns (bool) {
return _getAuthorizer().canPerform(actionId, account, address(this));
}
function _getAuthorizer() internal view returns (IAuthorizer) {
return vault.getAuthorizer();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "./BalancerErrors.sol";
import "../../vault/interfaces/IAsset.sol";
library InputHelpers {
function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
_require(a == b, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureInputLengthMatch(
uint256 a,
uint256 b,
uint256 c
) internal pure {
_require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
}
function ensureArrayIsSorted(IAsset[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(IERC20[] memory array) internal pure {
address[] memory addressArray;
// solhint-disable-next-line no-inline-assembly
assembly {
addressArray := array
}
ensureArrayIsSorted(addressArray);
}
function ensureArrayIsSorted(address[] memory array) internal pure {
if (array.length < 2) {
return;
}
address previous = array[0];
for (uint256 i = 1; i < array.length; ++i) {
address current = array[i];
_require(previous < current, Errors.UNSORTED_ARRAY);
previous = current;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
import "./IERC20.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 {
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @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).
*
* WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
*/
function _callOptionalReturn(address 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.
(bool success, bytes memory returndata) = token.call(data);
// If the low-level call didn't succeed we return whatever was returned from it.
assembly {
if eq(success, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
_require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/FixedPoint.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./ProtocolFeesCollector.sol";
import "./VaultAuthorization.sol";
import "./interfaces/IVault.sol";
/**
* @dev To reduce the bytecode size of the Vault, most of the protocol fee logic is not here, but in the
* ProtocolFeesCollector contract.
*/
abstract contract Fees is IVault {
using SafeERC20 for IERC20;
ProtocolFeesCollector private immutable _protocolFeesCollector;
constructor() {
_protocolFeesCollector = new ProtocolFeesCollector(IVault(this));
}
function getProtocolFeesCollector() public view override returns (ProtocolFeesCollector) {
return _protocolFeesCollector;
}
/**
* @dev Returns the protocol swap fee percentage.
*/
function _getProtocolSwapFeePercentage() internal view returns (uint256) {
return getProtocolFeesCollector().getSwapFeePercentage();
}
/**
* @dev Returns the protocol fee amount to charge for a flash loan of `amount`.
*/
function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) {
// Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged
// percentage can be slightly higher than intended.
uint256 percentage = getProtocolFeesCollector().getFlashLoanFeePercentage();
return FixedPoint.mulUp(amount, percentage);
}
function _payFeeAmount(IERC20 token, uint256 amount) internal {
if (amount > 0) {
token.safeTransfer(address(getProtocolFeesCollector()), amount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";
/* solhint-disable private-vars-leading-underscore */
library FixedPoint {
uint256 internal constant ONE = 1e18; // 18 decimal places
uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)
// Minimum base for the power function when the exponent is 'free' (larger than ONE).
uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
// Fixed Point addition is the same as regular checked addition
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
return product / ONE;
}
function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 product = a * b;
_require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
if (product == 0) {
return 0;
} else {
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((product - 1) / ONE) + 1;
}
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
return aInflated / b;
}
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
uint256 aInflated = a * ONE;
_require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow
// The traditional divUp formula is:
// divUp(x, y) := (x + y - 1) / y
// To avoid intermediate overflow in the addition, we distribute the division and get:
// divUp(x, y) := (x - 1) / y + 1
// Note that this requires x != 0, which we already tested for.
return ((aInflated - 1) / b) + 1;
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
* the true value (that is, the error function expected - actual is always positive).
*/
function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
if (raw < maxError) {
return 0;
} else {
return sub(raw, maxError);
}
}
/**
* @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
* the true value (that is, the error function expected - actual is always negative).
*/
function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 raw = LogExpMath.pow(x, y);
uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);
return add(raw, maxError);
}
/**
* @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
*
* Useful when computing the complement for values with some level of relative error, as it strips this error and
* prevents intermediate negative values.
*/
function complement(uint256 x) internal pure returns (uint256) {
return (x < ONE) ? (ONE - x) : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General internal License for more details.
// You should have received a copy of the GNU General internal License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/* solhint-disable */
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = ln_36(base);
} else {
logBase = ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = ln_36(arg);
} else {
logArg = ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* Adapted from OpenZeppelin's SafeMath library
*/
library Math {
/**
* @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
_require(c >= a, Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
_require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
_require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
return c;
}
/**
* @dev Returns the largest of two numbers of 256 bits.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers of 256 bits.
*/
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;
_require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
return c;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
return a / b;
}
function divUp(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b != 0, Errors.ZERO_DIVISION);
if (a == 0) {
return 0;
} else {
return 1 + (a - 1) / b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// Based on the EnumerableMap library from OpenZeppelin contracts, altered to include the following:
// * a map from IERC20 to bytes32
// * entries are stored in mappings instead of arrays, reducing implicit storage reads for out-of-bounds checks
// * unchecked_at and unchecked_valueAt, which allow for more gas efficient data reads in some scenarios
// * unchecked_indexOf and unchecked_setAt, which allow for more gas efficient data writes in some scenarios
//
// Additionally, the base private functions that work on bytes32 were removed and replaced with a native implementation
// for IERC20 keys, to reduce bytecode size and runtime costs.
// We're using non-standard casing for the unchecked functions to differentiate them, so we need to turn off that rule
// solhint-disable func-name-mixedcase
import "./IERC20.sol";
import "../helpers/BalancerErrors.sol";
/**
* @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;
* }
* ```
*/
library EnumerableMap {
// The original OpenZeppelin implementation uses a generic Map type with bytes32 keys: this was replaced with
// IERC20ToBytes32Map, which uses IERC20 keys natively, resulting in more dense bytecode.
struct IERC20ToBytes32MapEntry {
IERC20 _key;
bytes32 _value;
}
struct IERC20ToBytes32Map {
// Number of entries in the map
uint256 _length;
// Storage of map keys and values
mapping(uint256 => IERC20ToBytes32MapEntry) _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(IERC20 => 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(
IERC20ToBytes32Map storage map,
IERC20 key,
bytes32 value
) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to !contains(map, key)
if (keyIndex == 0) {
uint256 previousLength = map._length;
map._entries[previousLength] = IERC20ToBytes32MapEntry({ _key: key, _value: value });
map._length = previousLength + 1;
// The entry is stored at previousLength, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = previousLength + 1;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Updates the value for an entry, given its key's index. The key index can be retrieved via
* {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1).
*
* This function performs one less storage read than {set}, but it should only be used when `index` is known to be
* within bounds.
*/
function unchecked_setAt(
IERC20ToBytes32Map storage map,
uint256 index,
bytes32 value
) internal {
map._entries[index]._value = value;
}
/**
* @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(IERC20ToBytes32Map storage map, IERC20 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
// Equivalent to contains(map, key)
if (keyIndex != 0) {
// To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the
// one at the highest index, and then remove this last entry (sometimes called as 'swap and pop').
// This modifies the order of the pseudo-array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._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.
IERC20ToBytes32MapEntry 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
delete map._entries[lastIndex];
map._length = lastIndex;
// 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(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(IERC20ToBytes32Map storage map) internal view returns (uint256) {
return map._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(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
_require(map._length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(map, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) {
IERC20ToBytes32MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage
* read). O(1).
*/
function unchecked_valueAt(IERC20ToBytes32Map storage map, uint256 index) internal view returns (bytes32) {
return map._entries[index]._value;
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map. Reverts with `errorCode` otherwise.
*/
function get(
IERC20ToBytes32Map storage map,
IERC20 key,
uint256 errorCode
) internal view returns (bytes32) {
uint256 index = map._indexes[key];
_require(index > 0, errorCode);
return unchecked_valueAt(map, index - 1);
}
/**
* @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0
* instead.
*/
function unchecked_indexOf(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (uint256) {
return map._indexes[key];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
// Based on the EnumerableSet library from OpenZeppelin contracts, altered to remove the base private functions that
// work on bytes32, replacing them with a native implementation for address values, to reduce bytecode size and runtime
// costs.
// The `unchecked_at` function was also added, which allows for more gas efficient data reads in some scenarios.
/**
* @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 {
// The original OpenZeppelin implementation uses a generic Set type with bytes32 values: this was replaced with
// AddressSet, which uses address keys natively, resulting in more dense bytecode.
struct AddressSet {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(address => 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(AddressSet storage set, address value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
address 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(AddressSet storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
_require(set._values.length > index, Errors.OUT_OF_BOUNDS);
return unchecked_at(set, index);
}
/**
* @dev Same as {at}, except this doesn't revert if `index` it outside of the set (i.e. if it is equal or larger
* than {length}). O(1).
*
* This function performs one less storage read than {at}, but should only be used when `index` is known to be
* within bounds.
*/
function unchecked_at(AddressSet storage set, uint256 index) internal view returns (address) {
return set._values[index];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
_require(value < 2**255, Errors.SAFE_CAST_VALUE_CANT_FIT_INT256);
return int256(value);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./Fees.sol";
import "./PoolTokens.sol";
import "./UserBalance.sol";
import "./interfaces/IBasePool.sol";
/**
* @dev Stores the Asset Managers (by Pool and token), and implements the top level Asset Manager and Pool interfaces,
* such as registering and deregistering tokens, joining and exiting Pools, and informational functions like `getPool`
* and `getPoolTokens`, delegating to specialization-specific functions as needed.
*
* `managePoolBalance` handles all Asset Manager interactions.
*/
abstract contract PoolBalances is Fees, ReentrancyGuard, PoolTokens, UserBalance {
using Math for uint256;
using SafeERC20 for IERC20;
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable override whenNotPaused {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
// Note that `recipient` is not actually payable in the context of a join - we cast it because we handle both
// joins and exits at once.
_joinOrExit(PoolBalanceChangeKind.JOIN, poolId, sender, payable(recipient), _toPoolBalanceChange(request));
}
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external override {
// This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead.
_joinOrExit(PoolBalanceChangeKind.EXIT, poolId, sender, recipient, _toPoolBalanceChange(request));
}
// This has the exact same layout as JoinPoolRequest and ExitPoolRequest, except the `maxAmountsIn` and
// `minAmountsOut` are called `limits`. Internally we use this struct for both since these two functions are quite
// similar, but expose the others to callers for clarity.
struct PoolBalanceChange {
IAsset[] assets;
uint256[] limits;
bytes userData;
bool useInternalBalance;
}
/**
* @dev Converts a JoinPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(JoinPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Converts an ExitPoolRequest into a PoolBalanceChange, with no runtime cost.
*/
function _toPoolBalanceChange(ExitPoolRequest memory request)
private
pure
returns (PoolBalanceChange memory change)
{
// solhint-disable-next-line no-inline-assembly
assembly {
change := request
}
}
/**
* @dev Implements both `joinPool` and `exitPool`, based on `kind`.
*/
function _joinOrExit(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change
) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) {
// This function uses a large number of stack variables (poolId, sender and recipient, balances, amounts, fees,
// etc.), which leads to 'stack too deep' issues. It relies on private functions with seemingly arbitrary
// interfaces to work around this limitation.
InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length);
// We first check that the caller passed the Pool's registered tokens in the correct order, and retrieve the
// current balance for each.
IERC20[] memory tokens = _translateToIERC20(change.assets);
bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens);
// The bulk of the work is done here: the corresponding Pool hook is called, its final balances are computed,
// assets are transferred, and fees are paid.
(
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory paidProtocolSwapFeeAmounts
) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances);
// All that remains is storing the new Pool balances.
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances);
} else {
// PoolSpecialization.GENERAL
_setGeneralPoolBalances(poolId, finalBalances);
}
bool positive = kind == PoolBalanceChangeKind.JOIN; // Amounts in are positive, out are negative
emit PoolBalanceChanged(
poolId,
sender,
tokens,
// We can unsafely cast to int256 because balances are actually stored as uint112
_unsafeCastToInt256(amountsInOrOut, positive),
paidProtocolSwapFeeAmounts
);
}
/**
* @dev Calls the corresponding Pool hook to get the amounts in/out plus protocol fee amounts, and performs the
* associated token transfers and fee payments, returning the Pool's final balances.
*/
function _callPoolBalanceChange(
PoolBalanceChangeKind kind,
bytes32 poolId,
address sender,
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances
)
private
returns (
bytes32[] memory finalBalances,
uint256[] memory amountsInOrOut,
uint256[] memory dueProtocolFeeAmounts
)
{
(uint256[] memory totalBalances, uint256 lastChangeBlock) = balances.totalsAndLastChangeBlock();
IBasePool pool = IBasePool(_getPoolAddress(poolId));
(amountsInOrOut, dueProtocolFeeAmounts) = kind == PoolBalanceChangeKind.JOIN
? pool.onJoinPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
)
: pool.onExitPool(
poolId,
sender,
recipient,
totalBalances,
lastChangeBlock,
_getProtocolSwapFeePercentage(),
change.userData
);
InputHelpers.ensureInputLengthMatch(balances.length, amountsInOrOut.length, dueProtocolFeeAmounts.length);
// The Vault ignores the `recipient` in joins and the `sender` in exits: it is up to the Pool to keep track of
// their participation.
finalBalances = kind == PoolBalanceChangeKind.JOIN
? _processJoinPoolTransfers(sender, change, balances, amountsInOrOut, dueProtocolFeeAmounts)
: _processExitPoolTransfers(recipient, change, balances, amountsInOrOut, dueProtocolFeeAmounts);
}
/**
* @dev Transfers `amountsIn` from `sender`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees.
*
* Returns the Pool's final balances, which are the current balances plus `amountsIn` minus accumulated protocol
* swap fees.
*/
function _processJoinPoolTransfers(
address sender,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsIn,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 wrappedEth = 0;
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountIn = amountsIn[i];
_require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX);
// Receive assets from the sender - possibly from Internal Balance.
IAsset asset = change.assets[i];
_receiveAsset(asset, amountIn, sender, change.useInternalBalance);
if (_isETH(asset)) {
wrappedEth = wrappedEth.add(amountIn);
}
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. Note that the fee amount might be larger than `amountIn`,
// resulting in an overall decrease of the Pool's balance for a token.
finalBalances[i] = (amountIn >= feeAmount) // This lets us skip checked arithmetic
? balances[i].increaseCash(amountIn - feeAmount)
: balances[i].decreaseCash(feeAmount - amountIn);
}
// Handle any used and remaining ETH.
_handleRemainingEth(wrappedEth);
}
/**
* @dev Transfers `amountsOut` to `recipient`, checking that they are within their accepted limits, and pays
* accumulated protocol swap fees from the Pool.
*
* Returns the Pool's final balances, which are the current `balances` minus `amountsOut` and fees paid
* (`dueProtocolFeeAmounts`).
*/
function _processExitPoolTransfers(
address payable recipient,
PoolBalanceChange memory change,
bytes32[] memory balances,
uint256[] memory amountsOut,
uint256[] memory dueProtocolFeeAmounts
) private returns (bytes32[] memory finalBalances) {
finalBalances = new bytes32[](balances.length);
for (uint256 i = 0; i < change.assets.length; ++i) {
uint256 amountOut = amountsOut[i];
_require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN);
// Send tokens to the recipient - possibly to Internal Balance
IAsset asset = change.assets[i];
_sendAsset(asset, amountOut, recipient, change.useInternalBalance);
uint256 feeAmount = dueProtocolFeeAmounts[i];
_payFeeAmount(_translateToIERC20(asset), feeAmount);
// Compute the new Pool balances. A Pool's token balance always decreases after an exit (potentially by 0).
finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount));
}
}
/**
* @dev Returns the total balance for `poolId`'s `expectedTokens`.
*
* `expectedTokens` must exactly equal the token array returned by `getPoolTokens`: both arrays must have the same
* length, elements and order. Additionally, the Pool must have at least one registered token.
*/
function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens)
private
view
returns (bytes32[] memory)
{
(IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId);
InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length);
_require(actualTokens.length > 0, Errors.POOL_NO_TOKENS);
for (uint256 i = 0; i < actualTokens.length; ++i) {
_require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH);
}
return balances;
}
/**
* @dev Casts an array of uint256 to int256, setting the sign of the result according to the `positive` flag,
* without checking whether the values fit in the signed 256 bit range.
*/
function _unsafeCastToInt256(uint256[] memory values, bool positive)
private
pure
returns (int256[] memory signedValues)
{
signedValues = new int256[](values.length);
for (uint256 i = 0; i < values.length; i++) {
signedValues[i] = positive ? int256(values[i]) : -int256(values[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/openzeppelin/IERC20.sol";
import "./IVault.sol";
interface IPoolSwapStructs {
// This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
// IMinimalSwapInfoPool.
//
// This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
// 'given out') which indicates whether or not the amount sent by the pool is known.
//
// The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
// in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
//
// All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
// some Pools.
//
// `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
// one Pool.
//
// The meaning of `lastChangeBlock` depends on the Pool specialization:
// - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
// balance.
// - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
//
// `from` is the origin address for the funds the Pool receives, and `to` is the destination address
// where the Pool sends the outgoing tokens.
//
// `userData` is extra data provided by the caller - typically a signature from a trusted party.
struct SwapRequest {
IVault.SwapKind kind;
IERC20 tokenIn;
IERC20 tokenOut;
uint256 amount;
// Misc data
bytes32 poolId;
uint256 lastChangeBlock;
address from;
address to;
bytes userData;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev IPools with the General specialization setting should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will
* grant to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IGeneralPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IBasePool.sol";
/**
* @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
*
* This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
* Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
* to the pool in a 'given out' swap.
*
* This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
* changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
* indeed the Vault.
*/
interface IMinimalSwapInfoPool is IBasePool {
function onSwap(
SwapRequest memory swapRequest,
uint256 currentBalanceTokenIn,
uint256 currentBalanceTokenOut
) external returns (uint256 amount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/math/Math.sol";
// This library is used to create a data structure that represents a token's balance for a Pool. 'cash' is how many
// tokens the Pool has sitting inside of the Vault. 'managed' is how many tokens were withdrawn from the Vault by the
// Pool's Asset Manager. 'total' is the sum of these two, and represents the Pool's total token balance, including
// tokens that are *not* inside of the Vault.
//
// 'cash' is updated whenever tokens enter and exit the Vault, while 'managed' is only updated if the reason tokens are
// moving is due to an Asset Manager action. This is reflected in the different methods available: 'increaseCash'
// and 'decreaseCash' for swaps and add/remove liquidity events, and 'cashToManaged' and 'managedToCash' for events
// transferring funds to and from the Asset Manager.
//
// The Vault disallows the Pool's 'cash' from becoming negative. In other words, it can never use any tokens that are
// not inside the Vault.
//
// One of the goals of this library is to store the entire token balance in a single storage slot, which is why we use
// 112 bit unsigned integers for 'cash' and 'managed'. For consistency, we also disallow any combination of 'cash' and
// 'managed' that yields a 'total' that doesn't fit in 112 bits.
//
// The remaining 32 bits of the slot are used to store the most recent block when the total balance changed. This
// can be used to implement price oracles that are resilient to 'sandwich' attacks.
//
// We could use a Solidity struct to pack these three values together in a single storage slot, but unfortunately
// Solidity only allows for structs to live in either storage, calldata or memory. Because a memory struct still takes
// up a slot in the stack (to store its memory location), and because the entire balance fits in a single stack slot
// (two 112 bit values plus the 32 bit block), using memory is strictly less gas performant. Therefore, we do manual
// packing and unpacking.
//
// Since we cannot define new types, we rely on bytes32 to represent these values instead, as it doesn't have any
// associated arithmetic operations and therefore reduces the chance of misuse.
library BalanceAllocation {
using Math for uint256;
// The 'cash' portion of the balance is stored in the least significant 112 bits of a 256 bit word, while the
// 'managed' part uses the following 112 bits. The most significant 32 bits are used to store the block
/**
* @dev Returns the total amount of Pool tokens, including those that are not currently in the Vault ('managed').
*/
function total(bytes32 balance) internal pure returns (uint256) {
// Since 'cash' and 'managed' are 112 bit values, we don't need checked arithmetic. Additionally, `toBalance`
// ensures that 'total' always fits in 112 bits.
return cash(balance) + managed(balance);
}
/**
* @dev Returns the amount of Pool tokens currently in the Vault.
*/
function cash(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance) & mask;
}
/**
* @dev Returns the amount of Pool tokens that are being managed by an Asset Manager.
*/
function managed(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(balance >> 112) & mask;
}
/**
* @dev Returns the last block when the total balance changed.
*/
function lastChangeBlock(bytes32 balance) internal pure returns (uint256) {
uint256 mask = 2**(32) - 1;
return uint256(balance >> 224) & mask;
}
/**
* @dev Returns the difference in 'managed' between two balances.
*/
function managedDelta(bytes32 newBalance, bytes32 oldBalance) internal pure returns (int256) {
// Because `managed` is a 112 bit value, we can safely perform unchecked arithmetic in 256 bits.
return int256(managed(newBalance)) - int256(managed(oldBalance));
}
/**
* @dev Returns the total balance for each entry in `balances`, as well as the latest block when the total
* balance of *any* of them last changed.
*/
function totalsAndLastChangeBlock(bytes32[] memory balances)
internal
pure
returns (
uint256[] memory results,
uint256 lastChangeBlock_ // Avoid shadowing
)
{
results = new uint256[](balances.length);
lastChangeBlock_ = 0;
for (uint256 i = 0; i < results.length; i++) {
bytes32 balance = balances[i];
results[i] = total(balance);
lastChangeBlock_ = Math.max(lastChangeBlock_, lastChangeBlock(balance));
}
}
/**
* @dev Returns true if `balance`'s 'total' balance is zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isZero(bytes32 balance) internal pure returns (bool) {
// We simply need to check the least significant 224 bytes of the word: the block does not affect this.
uint256 mask = 2**(224) - 1;
return (uint256(balance) & mask) == 0;
}
/**
* @dev Returns true if `balance`'s 'total' balance is not zero. Costs less gas than computing 'total' and comparing
* with zero.
*/
function isNotZero(bytes32 balance) internal pure returns (bool) {
return !isZero(balance);
}
/**
* @dev Packs together `cash` and `managed` amounts with a block to create a balance value.
*
* For consistency, this also checks that the sum of `cash` and `managed` (`total`) fits in 112 bits.
*/
function toBalance(
uint256 _cash,
uint256 _managed,
uint256 _blockNumber
) internal pure returns (bytes32) {
uint256 _total = _cash + _managed;
// Since both 'cash' and 'managed' are positive integers, by checking that their sum ('total') fits in 112 bits
// we are also indirectly checking that both 'cash' and 'managed' themselves fit in 112 bits.
_require(_total >= _cash && _total < 2**112, Errors.BALANCE_TOTAL_OVERFLOW);
// We assume the block fits in 32 bits - this is expected to hold for at least a few decades.
return _pack(_cash, _managed, _blockNumber);
}
/**
* @dev Increases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent to the Vault (except
* for Asset Manager deposits).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function increaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Decreases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent from the Vault
* (except for Asset Manager withdrawals).
*
* Updates the last total balance change block, even if `amount` is zero.
*/
function decreaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 currentManaged = managed(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(newCash, currentManaged, newLastChangeBlock);
}
/**
* @dev Moves 'cash' into 'managed', leaving 'total' unchanged. Called when an Asset Manager withdraws Pool tokens
* from the Vault.
*/
function cashToManaged(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).sub(amount);
uint256 newManaged = managed(balance).add(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Moves 'managed' into 'cash', leaving 'total' unchanged. Called when an Asset Manager deposits Pool tokens
* into the Vault.
*/
function managedToCash(bytes32 balance, uint256 amount) internal pure returns (bytes32) {
uint256 newCash = cash(balance).add(amount);
uint256 newManaged = managed(balance).sub(amount);
uint256 currentLastChangeBlock = lastChangeBlock(balance);
return toBalance(newCash, newManaged, currentLastChangeBlock);
}
/**
* @dev Sets 'managed' balance to an arbitrary value, changing 'total'. Called when the Asset Manager reports
* profits or losses. It's the Manager's responsibility to provide a meaningful value.
*
* Updates the last total balance change block, even if `newManaged` is equal to the current 'managed' value.
*/
function setManaged(bytes32 balance, uint256 newManaged) internal view returns (bytes32) {
uint256 currentCash = cash(balance);
uint256 newLastChangeBlock = block.number;
return toBalance(currentCash, newManaged, newLastChangeBlock);
}
// Alternative mode for Pools with the Two Token specialization setting
// Instead of storing cash and external for each 'token in' a single storage slot, Two Token Pools store the cash
// for both tokens in the same slot, and the managed for both in another one. This reduces the gas cost for swaps,
// because the only slot that needs to be updated is the one with the cash. However, it also means that managing
// balances is more cumbersome, as both tokens need to be read/written at the same time.
//
// The field with both cash balances packed is called sharedCash, and the one with external amounts is called
// sharedManaged. These two are collectively called the 'shared' balance fields. In both of these, the portion
// that corresponds to token A is stored in the least significant 112 bits of a 256 bit word, while token B's part
// uses the next least significant 112 bits.
//
// Because only cash is written to during a swap, we store the last total balance change block with the
// packed cash fields. Typically Pools have a distinct block per token: in the case of Two Token Pools they
// are the same.
/**
* @dev Extracts the part of the balance that corresponds to token A. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceA(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance) & mask;
}
/**
* @dev Extracts the part of the balance that corresponds to token B. This function can be used to decode both
* shared cash and managed balances.
*/
function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) {
uint256 mask = 2**(112) - 1;
return uint256(sharedBalance >> 112) & mask;
}
// To decode the last balance change block, we can simply use the `blockNumber` function.
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token A.
*/
function fromSharedToBalanceA(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceA(sharedCash), _decodeBalanceA(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Unpacks the shared token A and token B cash and managed balances into the balance for token B.
*/
function fromSharedToBalanceB(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) {
// Note that we extract the block from the sharedCash field, which is the one that is updated by swaps.
// Both token A and token B use the same block
return toBalance(_decodeBalanceB(sharedCash), _decodeBalanceB(sharedManaged), lastChangeBlock(sharedCash));
}
/**
* @dev Returns the sharedCash shared field, given the current balances for token A and token B.
*/
function toSharedCash(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// Both balances are assigned the same block Since it is possible a single one of them has changed (for
// example, in an Asset Manager update), we keep the latest (largest) one.
uint32 newLastChangeBlock = uint32(Math.max(lastChangeBlock(tokenABalance), lastChangeBlock(tokenBBalance)));
return _pack(cash(tokenABalance), cash(tokenBBalance), newLastChangeBlock);
}
/**
* @dev Returns the sharedManaged shared field, given the current balances for token A and token B.
*/
function toSharedManaged(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) {
// We don't bother storing a last change block, as it is read from the shared cash field.
return _pack(managed(tokenABalance), managed(tokenBBalance), 0);
}
// Shared functions
/**
* @dev Packs together two uint112 and one uint32 into a bytes32
*/
function _pack(
uint256 _leastSignificant,
uint256 _midSignificant,
uint256 _mostSignificant
) private pure returns (bytes32) {
return bytes32((_mostSignificant << 224) + (_midSignificant << 112) + _leastSignificant);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./AssetManagers.sol";
import "./PoolRegistry.sol";
import "./balances/BalanceAllocation.sol";
abstract contract PoolTokens is ReentrancyGuard, PoolRegistry, AssetManagers {
using BalanceAllocation for bytes32;
using BalanceAllocation for bytes32[];
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external override nonReentrant whenNotPaused onlyPool(poolId) {
InputHelpers.ensureInputLengthMatch(tokens.length, assetManagers.length);
// Validates token addresses and assigns Asset Managers
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(token != IERC20(0), Errors.INVALID_TOKEN);
_poolAssetManagers[poolId][token] = assetManagers[i];
}
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_registerTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_registerMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_registerGeneralPoolTokens(poolId, tokens);
}
emit TokensRegistered(poolId, tokens, assetManagers);
}
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens)
external
override
nonReentrant
whenNotPaused
onlyPool(poolId)
{
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
_require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2);
_deregisterTwoTokenPoolTokens(poolId, tokens[0], tokens[1]);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_deregisterMinimalSwapInfoPoolTokens(poolId, tokens);
} else {
// PoolSpecialization.GENERAL
_deregisterGeneralPoolTokens(poolId, tokens);
}
// The deregister calls above ensure the total token balance is zero. Therefore it is now safe to remove any
// associated Asset Managers, since they hold no Pool balance.
for (uint256 i = 0; i < tokens.length; ++i) {
delete _poolAssetManagers[poolId][tokens[i]];
}
emit TokensDeregistered(poolId, tokens);
}
function getPoolTokens(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
)
{
bytes32[] memory rawBalances;
(tokens, rawBalances) = _getPoolTokens(poolId);
(balances, lastChangeBlock) = rawBalances.totalsAndLastChangeBlock();
}
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
override
withRegisteredPool(poolId)
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
)
{
bytes32 balance;
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
balance = _getTwoTokenPoolBalance(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
balance = _getMinimalSwapInfoPoolBalance(poolId, token);
} else {
// PoolSpecialization.GENERAL
balance = _getGeneralPoolBalance(poolId, token);
}
cash = balance.cash();
managed = balance.managed();
lastChangeBlock = balance.lastChangeBlock();
assetManager = _poolAssetManagers[poolId][token];
}
/**
* @dev Returns all of `poolId`'s registered tokens, along with their raw balances.
*/
function _getPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _getTwoTokenPoolTokens(poolId);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _getMinimalSwapInfoPoolTokens(poolId);
} else {
// PoolSpecialization.GENERAL
return _getGeneralPoolTokens(poolId);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/math/Math.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "../lib/openzeppelin/SafeCast.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "./AssetTransfersHandler.sol";
import "./VaultAuthorization.sol";
/**
* Implement User Balance interactions, which combine Internal Balance and using the Vault's ERC20 allowance.
*
* Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
* transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
* when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
* gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
*
* Internal Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different senders and recipients, at once.
*/
abstract contract UserBalance is ReentrancyGuard, AssetTransfersHandler, VaultAuthorization {
using Math for uint256;
using SafeCast for uint256;
using SafeERC20 for IERC20;
// Internal Balance for each token, for each account.
mapping(address => mapping(IERC20 => uint256)) private _internalTokenBalance;
function getInternalBalance(address user, IERC20[] memory tokens)
external
view
override
returns (uint256[] memory balances)
{
balances = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
balances[i] = _getInternalBalance(user, tokens[i]);
}
}
function manageUserBalance(UserBalanceOp[] memory ops) external payable override nonReentrant {
// We need to track how much of the received ETH was used and wrapped into WETH to return any excess.
uint256 ethWrapped = 0;
// Cache for these checks so we only perform them once (if at all).
bool checkedCallerIsRelayer = false;
bool checkedNotPaused = false;
for (uint256 i = 0; i < ops.length; i++) {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
// This destructuring by calling `_validateUserBalanceOp` seems odd, but results in reduced bytecode size.
(kind, asset, amount, sender, recipient, checkedCallerIsRelayer) = _validateUserBalanceOp(
ops[i],
checkedCallerIsRelayer
);
if (kind == UserBalanceOpKind.WITHDRAW_INTERNAL) {
// Internal Balance withdrawals can always be performed by an authorized account.
_withdrawFromInternalBalance(asset, sender, recipient, amount);
} else {
// All other operations are blocked if the contract is paused.
// We cache the result of the pause check and skip it for other operations in this same transaction
// (if any).
if (!checkedNotPaused) {
_ensureNotPaused();
checkedNotPaused = true;
}
if (kind == UserBalanceOpKind.DEPOSIT_INTERNAL) {
_depositToInternalBalance(asset, sender, recipient, amount);
// Keep track of all ETH wrapped into WETH as part of a deposit.
if (_isETH(asset)) {
ethWrapped = ethWrapped.add(amount);
}
} else {
// Transfers don't support ETH.
_require(!_isETH(asset), Errors.CANNOT_USE_ETH_SENTINEL);
IERC20 token = _asIERC20(asset);
if (kind == UserBalanceOpKind.TRANSFER_INTERNAL) {
_transferInternalBalance(token, sender, recipient, amount);
} else {
// TRANSFER_EXTERNAL
_transferToExternalBalance(token, sender, recipient, amount);
}
}
}
}
// Handle any remaining ETH.
_handleRemainingEth(ethWrapped);
}
function _depositToInternalBalance(
IAsset asset,
address sender,
address recipient,
uint256 amount
) private {
_increaseInternalBalance(recipient, _translateToIERC20(asset), amount);
_receiveAsset(asset, amount, sender, false);
}
function _withdrawFromInternalBalance(
IAsset asset,
address sender,
address payable recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, _translateToIERC20(asset), amount, false);
_sendAsset(asset, amount, recipient, false);
}
function _transferInternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
// A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`.
_decreaseInternalBalance(sender, token, amount, false);
_increaseInternalBalance(recipient, token, amount);
}
function _transferToExternalBalance(
IERC20 token,
address sender,
address recipient,
uint256 amount
) private {
if (amount > 0) {
token.safeTransferFrom(sender, recipient, amount);
emit ExternalBalanceTransfer(token, sender, recipient, amount);
}
}
/**
* @dev Increases `account`'s Internal Balance for `token` by `amount`.
*/
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal override {
uint256 currentBalance = _getInternalBalance(account, token);
uint256 newBalance = currentBalance.add(amount);
_setInternalBalance(account, token, newBalance, amount.toInt256());
}
/**
* @dev Decreases `account`'s Internal Balance for `token` by `amount`. If `allowPartial` is true, this function
* doesn't revert if `account` doesn't have enough balance, and sets it to zero and returns the deducted amount
* instead.
*/
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool allowPartial
) internal override returns (uint256 deducted) {
uint256 currentBalance = _getInternalBalance(account, token);
_require(allowPartial || (currentBalance >= amount), Errors.INSUFFICIENT_INTERNAL_BALANCE);
deducted = Math.min(currentBalance, amount);
// By construction, `deducted` is lower or equal to `currentBalance`, so we don't need to use checked
// arithmetic.
uint256 newBalance = currentBalance - deducted;
_setInternalBalance(account, token, newBalance, -(deducted.toInt256()));
}
/**
* @dev Sets `account`'s Internal Balance for `token` to `newBalance`.
*
* Emits an `InternalBalanceChanged` event. This event includes `delta`, which is the amount the balance increased
* (if positive) or decreased (if negative). To avoid reading the current balance in order to compute the delta,
* this function relies on the caller providing it directly.
*/
function _setInternalBalance(
address account,
IERC20 token,
uint256 newBalance,
int256 delta
) private {
_internalTokenBalance[account][token] = newBalance;
emit InternalBalanceChanged(account, token, delta);
}
/**
* @dev Returns `account`'s Internal Balance for `token`.
*/
function _getInternalBalance(address account, IERC20 token) internal view returns (uint256) {
return _internalTokenBalance[account][token];
}
/**
* @dev Destructures a User Balance operation, validating that the contract caller is allowed to perform it.
*/
function _validateUserBalanceOp(UserBalanceOp memory op, bool checkedCallerIsRelayer)
private
view
returns (
UserBalanceOpKind,
IAsset,
uint256,
address,
address payable,
bool
)
{
// The only argument we need to validate is `sender`, which can only be either the contract caller, or a
// relayer approved by `sender`.
address sender = op.sender;
if (sender != msg.sender) {
// We need to check both that the contract caller is a relayer, and that `sender` approved them.
// Because the relayer check is global (i.e. independent of `sender`), we cache that result and skip it for
// other operations in this same transaction (if any).
if (!checkedCallerIsRelayer) {
_authenticateCaller();
checkedCallerIsRelayer = true;
}
_require(_hasApprovedRelayer(sender, msg.sender), Errors.USER_DOESNT_ALLOW_RELAYER);
}
return (op.kind, op.asset, op.amount, sender, op.recipient, checkedCallerIsRelayer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./IVault.sol";
import "./IPoolSwapStructs.sol";
/**
* @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
* the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
* either IGeneralPool or IMinimalSwapInfoPool
*/
interface IBasePool is IPoolSwapStructs {
/**
* @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
* each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
* The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
* the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
*
* Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
*
* `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
* designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances
* for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as minting pool shares.
*/
function onJoinPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);
/**
* @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
* tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
* to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
* as well as collect the reported amount in protocol fees, which the Pool should calculate based on
* `protocolSwapFeePercentage`.
*
* Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
*
* `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
* to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token
* the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
*
* `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
* balance.
*
* `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
* exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
*
* Contracts implementing this function should check that the caller is indeed the Vault before performing any
* state-changing operations, such as burning pool shares.
*/
function onExitPool(
bytes32 poolId,
address sender,
address recipient,
uint256[] memory balances,
uint256 lastChangeBlock,
uint256 protocolSwapFeePercentage,
bytes memory userData
) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/helpers/InputHelpers.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./UserBalance.sol";
import "./balances/BalanceAllocation.sol";
import "./balances/GeneralPoolsBalance.sol";
import "./balances/MinimalSwapInfoPoolsBalance.sol";
import "./balances/TwoTokenPoolsBalance.sol";
abstract contract AssetManagers is
ReentrancyGuard,
GeneralPoolsBalance,
MinimalSwapInfoPoolsBalance,
TwoTokenPoolsBalance
{
using Math for uint256;
using SafeERC20 for IERC20;
// Stores the Asset Manager for each token of each Pool.
mapping(bytes32 => mapping(IERC20 => address)) internal _poolAssetManagers;
function managePoolBalance(PoolBalanceOp[] memory ops) external override nonReentrant whenNotPaused {
// This variable could be declared inside the loop, but that causes the compiler to allocate memory on each
// loop iteration, increasing gas costs.
PoolBalanceOp memory op;
for (uint256 i = 0; i < ops.length; ++i) {
// By indexing the array only once, we don't spend extra gas in the same bounds check.
op = ops[i];
bytes32 poolId = op.poolId;
_ensureRegisteredPool(poolId);
IERC20 token = op.token;
_require(_isTokenRegistered(poolId, token), Errors.TOKEN_NOT_REGISTERED);
_require(_poolAssetManagers[poolId][token] == msg.sender, Errors.SENDER_NOT_ASSET_MANAGER);
PoolBalanceOpKind kind = op.kind;
uint256 amount = op.amount;
(int256 cashDelta, int256 managedDelta) = _performPoolManagementOperation(kind, poolId, token, amount);
emit PoolBalanceManaged(poolId, msg.sender, token, cashDelta, managedDelta);
}
}
/**
* @dev Performs the `kind` Asset Manager operation on a Pool.
*
* Withdrawals will transfer `amount` tokens to the caller, deposits will transfer `amount` tokens from the caller,
* and updates will set the managed balance to `amount`.
*
* Returns a tuple with the 'cash' and 'managed' balance deltas as a result of this call.
*/
function _performPoolManagementOperation(
PoolBalanceOpKind kind,
bytes32 poolId,
IERC20 token,
uint256 amount
) private returns (int256, int256) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (kind == PoolBalanceOpKind.WITHDRAW) {
return _withdrawPoolBalance(poolId, specialization, token, amount);
} else if (kind == PoolBalanceOpKind.DEPOSIT) {
return _depositPoolBalance(poolId, specialization, token, amount);
} else {
// PoolBalanceOpKind.UPDATE
return _updateManagedBalance(poolId, specialization, token, amount);
}
}
/**
* @dev Moves `amount` tokens from a Pool's 'cash' to 'managed' balance, and transfers them to the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _withdrawPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolCashToManaged(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolCashToManaged(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolCashToManaged(poolId, token, amount);
}
if (amount > 0) {
token.safeTransfer(msg.sender, amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(-amount);
managedDelta = int256(amount);
}
/**
* @dev Moves `amount` tokens from a Pool's 'managed' to 'cash' balance, and transfers them from the caller.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary.
*/
function _depositPoolBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
_twoTokenPoolManagedToCash(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
_minimalSwapInfoPoolManagedToCash(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
_generalPoolManagedToCash(poolId, token, amount);
}
if (amount > 0) {
token.safeTransferFrom(msg.sender, address(this), amount);
}
// Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will
// therefore always fit in a 256 bit integer.
cashDelta = int256(amount);
managedDelta = int256(-amount);
}
/**
* @dev Sets a Pool's 'managed' balance to `amount`.
*
* Returns the 'cash' and 'managed' balance deltas as a result of this call (the 'cash' delta will always be zero).
*/
function _updateManagedBalance(
bytes32 poolId,
PoolSpecialization specialization,
IERC20 token,
uint256 amount
) private returns (int256 cashDelta, int256 managedDelta) {
if (specialization == PoolSpecialization.TWO_TOKEN) {
managedDelta = _setTwoTokenPoolManagedBalance(poolId, token, amount);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
managedDelta = _setMinimalSwapInfoPoolManagedBalance(poolId, token, amount);
} else {
// PoolSpecialization.GENERAL
managedDelta = _setGeneralPoolManagedBalance(poolId, token, amount);
}
cashDelta = 0;
}
/**
* @dev Returns true if `token` is registered for `poolId`.
*/
function _isTokenRegistered(bytes32 poolId, IERC20 token) private view returns (bool) {
PoolSpecialization specialization = _getPoolSpecialization(poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
return _isTwoTokenPoolTokenRegistered(poolId, token);
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
return _isMinimalSwapInfoPoolTokenRegistered(poolId, token);
} else {
// PoolSpecialization.GENERAL
return _isGeneralPoolTokenRegistered(poolId, token);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/ReentrancyGuard.sol";
import "./VaultAuthorization.sol";
/**
* @dev Maintains the Pool ID data structure, implements Pool ID creation and registration, and defines useful modifiers
* and helper functions for ensuring correct behavior when working with Pools.
*/
abstract contract PoolRegistry is ReentrancyGuard, VaultAuthorization {
// Each pool is represented by their unique Pool ID. We use `bytes32` for them, for lack of a way to define new
// types.
mapping(bytes32 => bool) private _isPoolRegistered;
// We keep an increasing nonce to make Pool IDs unique. It is interpreted as a `uint80`, but storing it as a
// `uint256` results in reduced bytecode on reads and writes due to the lack of masking.
uint256 private _nextPoolNonce;
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
modifier withRegisteredPool(bytes32 poolId) {
_ensureRegisteredPool(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
modifier onlyPool(bytes32 poolId) {
_ensurePoolIsSender(poolId);
_;
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool.
*/
function _ensureRegisteredPool(bytes32 poolId) internal view {
_require(_isPoolRegistered[poolId], Errors.INVALID_POOL_ID);
}
/**
* @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract.
*/
function _ensurePoolIsSender(bytes32 poolId) private view {
_ensureRegisteredPool(poolId);
_require(msg.sender == _getPoolAddress(poolId), Errors.CALLER_NOT_POOL);
}
function registerPool(PoolSpecialization specialization)
external
override
nonReentrant
whenNotPaused
returns (bytes32)
{
// Each Pool is assigned a unique ID based on an incrementing nonce. This assumes there will never be more than
// 2**80 Pools, and the nonce will not overflow.
bytes32 poolId = _toPoolId(msg.sender, specialization, uint80(_nextPoolNonce));
_require(!_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); // Should never happen as Pool IDs are unique.
_isPoolRegistered[poolId] = true;
_nextPoolNonce += 1;
// Note that msg.sender is the pool's contract
emit PoolRegistered(poolId, msg.sender, specialization);
return poolId;
}
function getPool(bytes32 poolId)
external
view
override
withRegisteredPool(poolId)
returns (address, PoolSpecialization)
{
return (_getPoolAddress(poolId), _getPoolSpecialization(poolId));
}
/**
* @dev Creates a Pool ID.
*
* These are deterministically created by packing the Pool's contract address and its specialization setting into
* the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses.
*
* Since a single contract can register multiple Pools, a unique nonce must be provided to ensure Pool IDs are
* unique.
*
* Pool IDs have the following layout:
* | 20 bytes pool contract address | 2 bytes specialization setting | 10 bytes nonce |
* MSB LSB
*
* 2 bytes for the specialization setting is a bit overkill: there only three of them, which means two bits would
* suffice. However, there's nothing else of interest to store in this extra space.
*/
function _toPoolId(
address pool,
PoolSpecialization specialization,
uint80 nonce
) internal pure returns (bytes32) {
bytes32 serialized;
serialized |= bytes32(uint256(nonce));
serialized |= bytes32(uint256(specialization)) << (10 * 8);
serialized |= bytes32(uint256(pool)) << (12 * 8);
return serialized;
}
/**
* @dev Returns the address of a Pool's contract.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolAddress(bytes32 poolId) internal pure returns (address) {
// 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask,
// since the logical shift already sets the upper bits to zero.
return address(uint256(poolId) >> (12 * 8));
}
/**
* @dev Returns the specialization setting of a Pool.
*
* Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.
*/
function _getPoolSpecialization(bytes32 poolId) internal pure returns (PoolSpecialization specialization) {
// 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address.
uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1);
// Casting a value into an enum results in a runtime check that reverts unless the value is within the enum's
// range. Passing an invalid Pool ID to this function would then result in an obscure revert with no reason
// string: we instead perform the check ourselves to help in error diagnosis.
// There are three Pool specialization settings: general, minimal swap info and two tokens, which correspond to
// values 0, 1 and 2.
_require(value < 3, Errors.INVALID_POOL_ID);
// Because we have checked that `value` is within the enum range, we can use assembly to skip the runtime check.
// solhint-disable-next-line no-inline-assembly
assembly {
specialization := value
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableMap.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
abstract contract GeneralPoolsBalance {
using BalanceAllocation for bytes32;
using EnumerableMap for EnumerableMap.IERC20ToBytes32Map;
// Data for Pools with the General specialization setting
//
// These Pools use the IGeneralPool interface, which means the Vault must query the balance for *all* of their
// tokens in every swap. If we kept a mapping of token to balance plus a set (array) of tokens, it'd be very gas
// intensive to read all token addresses just to then do a lookup on the balance mapping.
//
// Instead, we use our customized EnumerableMap, which lets us read the N balances in N+1 storage accesses (one for
// each token in the Pool), access the index of any 'token in' a single read (required for the IGeneralPool call),
// and update an entry's value given its index.
// Map of token -> balance pairs for each Pool with this specialization. Many functions rely on storage pointers to
// a Pool's EnumerableMap to save gas when computing storage slots.
mapping(bytes32 => EnumerableMap.IERC20ToBytes32Map) internal _generalPoolsBalances;
/**
* @dev Registers a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
// EnumerableMaps require an explicit initial value when creating a key-value pair: we use zero, the same
// value that is found in uninitialized storage, which corresponds to an empty balance.
bool added = poolBalances.set(tokens[i], 0);
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
}
}
/**
* @dev Deregisters a list of tokens in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
_require(currentBalance.isZero(), Errors.NONZERO_TOKEN_BALANCE);
// We don't need to check remove's return value, since _getGeneralPoolBalance already checks that the token
// was registered.
poolBalances.remove(token);
}
}
/**
* @dev Sets the balances of a General Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setGeneralPoolBalances(bytes32 poolId, bytes32[] memory balances) internal {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
for (uint256 i = 0; i < balances.length; ++i) {
// Since we assume all balances are properly ordered, we can simply use `unchecked_setAt` to avoid one less
// storage read per token.
poolBalances.unchecked_setAt(i, balances[i]);
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a General Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*/
function _generalPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateGeneralPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a General Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setGeneralPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateGeneralPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a General Pool to the result of the `mutation` function when called with the
* current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateGeneralPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token);
bytes32 newBalance = mutation(currentBalance, amount);
poolBalances.set(token, newBalance);
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a General Pool. The order may change when tokens are
* registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _getGeneralPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
tokens = new IERC20[](poolBalances.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableMap's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
(tokens[i], balances[i]) = poolBalances.unchecked_at(i);
}
}
/**
* @dev Returns the balance of a token in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getGeneralPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return _getGeneralPoolBalance(poolBalances, token);
}
/**
* @dev Same as `_getGeneralPoolBalance` but using a Pool's storage pointer, which saves gas in repeated reads and
* writes.
*/
function _getGeneralPoolBalance(EnumerableMap.IERC20ToBytes32Map storage poolBalances, IERC20 token)
private
view
returns (bytes32)
{
return poolBalances.get(token, Errors.TOKEN_NOT_REGISTERED);
}
/**
* @dev Returns true if `token` is registered in a General Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*/
function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId];
return poolBalances.contains(token);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/EnumerableSet.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract MinimalSwapInfoPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
using EnumerableSet for EnumerableSet.AddressSet;
// Data for Pools with the Minimal Swap Info specialization setting
//
// These Pools use the IMinimalSwapInfoPool interface, and so the Vault must read the balance of the two tokens
// in the swap. The best solution is to use a mapping from token to balance, which lets us read or write any token's
// balance in a single storage access.
//
// We also keep a set of registered tokens. Because tokens with non-zero balance are by definition registered, in
// some balance getters we skip checking for token registration if a non-zero balance is found, saving gas by
// performing a single read instead of two.
mapping(bytes32 => mapping(IERC20 => bytes32)) internal _minimalSwapInfoPoolsBalances;
mapping(bytes32 => EnumerableSet.AddressSet) internal _minimalSwapInfoPoolsTokens;
/**
* @dev Registers a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must not be registered in the Pool
* - `tokens` must not contain duplicates
*/
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
bool added = poolTokens.add(address(tokens[i]));
_require(added, Errors.TOKEN_ALREADY_REGISTERED);
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
}
/**
* @dev Deregisters a list of tokens in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*
* Requirements:
*
* - `tokens` must be registered in the Pool
* - `tokens` must have zero balance in the Vault
* - `tokens` must not contain duplicates
*/
function _deregisterMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
for (uint256 i = 0; i < tokens.length; ++i) {
IERC20 token = tokens[i];
_require(_minimalSwapInfoPoolsBalances[poolId][token].isZero(), Errors.NONZERO_TOKEN_BALANCE);
// For consistency with other Pool specialization settings, we explicitly reset the balance (which may have
// a non-zero last change block).
delete _minimalSwapInfoPoolsBalances[poolId][token];
bool removed = poolTokens.remove(address(token));
_require(removed, Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Sets the balances of a Minimal Swap Info Pool's tokens to `balances`.
*
* WARNING: this assumes `balances` has the same length and order as the Pool's tokens.
*/
function _setMinimalSwapInfoPoolBalances(
bytes32 poolId,
IERC20[] memory tokens,
bytes32[] memory balances
) internal {
for (uint256 i = 0; i < tokens.length; ++i) {
_minimalSwapInfoPoolsBalances[poolId][tokens[i]] = balances[i];
}
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*/
function _minimalSwapInfoPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Minimal Swap Info Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setMinimalSwapInfoPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Minimal Swap Info Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that
* `token` is registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateMinimalSwapInfoPoolBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) internal returns (int256) {
bytes32 currentBalance = _getMinimalSwapInfoPoolBalance(poolId, token);
bytes32 newBalance = mutation(currentBalance, amount);
_minimalSwapInfoPoolsBalances[poolId][token] = newBalance;
return newBalance.managedDelta(currentBalance);
}
/**
* @dev Returns an array with all the tokens and balances in a Minimal Swap Info Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _getMinimalSwapInfoPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
tokens = new IERC20[](poolTokens.length());
balances = new bytes32[](tokens.length);
for (uint256 i = 0; i < tokens.length; ++i) {
// Because the iteration is bounded by `tokens.length`, which matches the EnumerableSet's length, we can use
// `unchecked_at` as we know `i` is a valid token index, saving storage reads.
IERC20 token = IERC20(poolTokens.unchecked_at(i));
tokens[i] = token;
balances[i] = _minimalSwapInfoPoolsBalances[poolId][token];
}
}
/**
* @dev Returns the balance of a token in a Minimal Swap Info Pool.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `token` must be registered in the Pool
*/
function _getMinimalSwapInfoPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
bytes32 balance = _minimalSwapInfoPoolsBalances[poolId][token];
// A non-zero balance guarantees that the token is registered. If zero, we manually check if the token is
// registered in the Pool. Token registration implies that the Pool is registered as well, which lets us save
// gas by not performing the check.
bool tokenRegistered = balance.isNotZero() || _minimalSwapInfoPoolsTokens[poolId].contains(address(token));
if (!tokenRegistered) {
// The token might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
return balance;
}
/**
* @dev Returns true if `token` is registered in a Minimal Swap Info Pool.
*
* This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting.
*/
function _isMinimalSwapInfoPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId];
return poolTokens.contains(address(token));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../../lib/helpers/BalancerErrors.sol";
import "../../lib/openzeppelin/IERC20.sol";
import "./BalanceAllocation.sol";
import "../PoolRegistry.sol";
abstract contract TwoTokenPoolsBalance is PoolRegistry {
using BalanceAllocation for bytes32;
// Data for Pools with the Two Token specialization setting
//
// These are similar to the Minimal Swap Info Pool case (because the Pool only has two tokens, and therefore there
// are only two balances to read), but there's a key difference in how data is stored. Keeping a set makes little
// sense, as it will only ever hold two tokens, so we can just store those two directly.
//
// The gas savings associated with using these Pools come from how token balances are stored: cash amounts for token
// A and token B are packed together, as are managed amounts. Because only cash changes in a swap, there's no need
// to write to this second storage slot. A single last change block number for both tokens is stored with the packed
// cash fields.
struct TwoTokenPoolBalances {
bytes32 sharedCash;
bytes32 sharedManaged;
}
// We could just keep a mapping from Pool ID to TwoTokenSharedBalances, but there's an issue: we wouldn't know to
// which tokens those balances correspond. This would mean having to also check which are registered with the Pool.
//
// What we do instead to save those storage reads is keep a nested mapping from the token pair hash to the balances
// struct. The Pool only has two tokens, so only a single entry of this mapping is set (the one that corresponds to
// that pair's hash).
//
// This has the trade-off of making Vault code that interacts with these Pools cumbersome: both balances must be
// accessed at the same time by using both token addresses, and some logic is needed to determine how the pair hash
// is computed. We do this by sorting the tokens, calling the token with the lowest numerical address value token A,
// and the other one token B. In functions where the token arguments could be either A or B, we use X and Y instead.
//
// If users query a token pair containing an unregistered token, the Pool will generate a hash for a mapping entry
// that was not set, and return zero balances. Non-zero balances are only possible if both tokens in the pair
// are registered with the Pool, which means we don't have to check the TwoTokenPoolTokens struct, and can save
// storage reads.
struct TwoTokenPoolTokens {
IERC20 tokenA;
IERC20 tokenB;
mapping(bytes32 => TwoTokenPoolBalances) balances;
}
mapping(bytes32 => TwoTokenPoolTokens) private _twoTokenPoolTokens;
/**
* @dev Registers tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must not be the same
* - The tokens must be ordered: tokenX < tokenY
*/
function _registerTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
// Not technically true since we didn't register yet, but this is consistent with the error messages of other
// specialization settings.
_require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);
_require(tokenX < tokenY, Errors.UNSORTED_TOKENS);
// A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B.
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
_require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET);
// Since tokenX < tokenY, tokenX is A and tokenY is B
poolTokens.tokenA = tokenX;
poolTokens.tokenB = tokenY;
// Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty
// balance.
}
/**
* @dev Deregisters tokens in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*
* Requirements:
*
* - `tokenX` and `tokenY` must be registered in the Pool
* - both tokens must have zero balance in the Vault
*/
function _deregisterTwoTokenPoolTokens(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
) internal {
(
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY);
_require(balanceA.isZero() && balanceB.isZero(), Errors.NONZERO_TOKEN_BALANCE);
delete _twoTokenPoolTokens[poolId];
// For consistency with other Pool specialization settings, we explicitly reset the packed cash field (which may
// have a non-zero last change block).
delete poolBalances.sharedCash;
}
/**
* @dev Sets the cash balances of a Two Token Pool's tokens.
*
* WARNING: this assumes `tokenA` and `tokenB` are the Pool's two registered tokens, and are in the correct order.
*/
function _setTwoTokenPoolCashBalances(
bytes32 poolId,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
) internal {
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
TwoTokenPoolBalances storage poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
poolBalances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from cash into managed.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
/**
* @dev Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*/
function _twoTokenPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.managedToCash, amount);
}
/**
* @dev Sets `token`'s managed balance in a Two Token Pool to `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _setTwoTokenPoolManagedBalance(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal returns (int256) {
return _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.setManaged, amount);
}
/**
* @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with
* the current balance and `amount`.
*
* This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is
* registered for that Pool.
*
* Returns the managed balance delta as a result of this call.
*/
function _updateTwoTokenPoolSharedBalance(
bytes32 poolId,
IERC20 token,
function(bytes32, uint256) returns (bytes32) mutation,
uint256 amount
) private returns (int256) {
(
TwoTokenPoolBalances storage balances,
IERC20 tokenA,
bytes32 balanceA,
,
bytes32 balanceB
) = _getTwoTokenPoolBalances(poolId);
int256 delta;
if (token == tokenA) {
bytes32 newBalance = mutation(balanceA, amount);
delta = newBalance.managedDelta(balanceA);
balanceA = newBalance;
} else {
// token == tokenB
bytes32 newBalance = mutation(balanceB, amount);
delta = newBalance.managedDelta(balanceB);
balanceB = newBalance;
}
balances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);
balances.sharedManaged = BalanceAllocation.toSharedManaged(balanceA, balanceB);
return delta;
}
/*
* @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when
* tokens are registered or deregistered.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _getTwoTokenPoolTokens(bytes32 poolId)
internal
view
returns (IERC20[] memory tokens, bytes32[] memory balances)
{
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
// Both tokens will either be zero (if unregistered) or non-zero (if registered), but we keep the full check for
// clarity.
if (tokenA == IERC20(0) || tokenB == IERC20(0)) {
return (new IERC20[](0), new bytes32[](0));
}
// Note that functions relying on this getter expect tokens to be properly ordered, so we use the (A, B)
// ordering.
tokens = new IERC20[](2);
tokens[0] = tokenA;
tokens[1] = tokenB;
balances = new bytes32[](2);
balances[0] = balanceA;
balances[1] = balanceB;
}
/**
* @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using
* an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it
* without having to recompute the pair hash and storage slot.
*/
function _getTwoTokenPoolBalances(bytes32 poolId)
private
view
returns (
TwoTokenPoolBalances storage poolBalances,
IERC20 tokenA,
bytes32 balanceA,
IERC20 tokenB,
bytes32 balanceB
)
{
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
tokenA = poolTokens.tokenA;
tokenB = poolTokens.tokenB;
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = poolTokens.balances[pairHash];
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns the balance of a token in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the General specialization setting.
*
* This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive
* operations, such as swaps. For those, _getTwoTokenPoolSharedBalances provides a more flexible interface.
*
* Requirements:
*
* - `token` must be registered in the Pool
*/
function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {
// We can't just read the balance of token, because we need to know the full pair in order to compute the pair
// hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`.
(, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);
if (token == tokenA) {
return balanceA;
} else if (token == tokenB) {
return balanceB;
} else {
_revert(Errors.TOKEN_NOT_REGISTERED);
}
}
/**
* @dev Returns the balance of the two tokens in a Two Token Pool.
*
* The returned balances are those of token A and token B, where token A is the lowest of token X and token Y, and
* token B the other.
*
* This function also returns a storage pointer to the TwoTokenPoolBalances struct associated with the token pair,
* which can be used to update it without having to recompute the pair hash and storage slot.
*
* Requirements:
*
* - `poolId` must be a Minimal Swap Info Pool
* - `tokenX` and `tokenY` must be registered in the Pool
*/
function _getTwoTokenPoolSharedBalances(
bytes32 poolId,
IERC20 tokenX,
IERC20 tokenY
)
internal
view
returns (
bytes32 balanceA,
bytes32 balanceB,
TwoTokenPoolBalances storage poolBalances
)
{
(IERC20 tokenA, IERC20 tokenB) = _sortTwoTokens(tokenX, tokenY);
bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);
poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash];
// Because we're reading balances using the pair hash, if either token X or token Y is not registered then
// *both* balance entries will be zero.
bytes32 sharedCash = poolBalances.sharedCash;
bytes32 sharedManaged = poolBalances.sharedManaged;
// A non-zero balance guarantees that both tokens are registered. If zero, we manually check whether each
// token is registered in the Pool. Token registration implies that the Pool is registered as well, which
// lets us save gas by not performing the check.
bool tokensRegistered = sharedCash.isNotZero() ||
sharedManaged.isNotZero() ||
(_isTwoTokenPoolTokenRegistered(poolId, tokenA) && _isTwoTokenPoolTokenRegistered(poolId, tokenB));
if (!tokensRegistered) {
// The tokens might not be registered because the Pool itself is not registered. We check this to provide a
// more accurate revert reason.
_ensureRegisteredPool(poolId);
_revert(Errors.TOKEN_NOT_REGISTERED);
}
balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);
balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);
}
/**
* @dev Returns true if `token` is registered in a Two Token Pool.
*
* This function assumes `poolId` exists and corresponds to the Two Token specialization setting.
*/
function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {
TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];
// The zero address can never be a registered token.
return (token == poolTokens.tokenA || token == poolTokens.tokenB) && token != IERC20(0);
}
/**
* @dev Returns the hash associated with a given token pair.
*/
function _getTwoTokenPairHash(IERC20 tokenA, IERC20 tokenB) private pure returns (bytes32) {
return keccak256(abi.encodePacked(tokenA, tokenB));
}
/**
* @dev Sorts two tokens in ascending order, returning them as a (tokenA, tokenB) tuple.
*/
function _sortTwoTokens(IERC20 tokenX, IERC20 tokenY) private pure returns (IERC20, IERC20) {
return tokenX < tokenY ? (tokenX, tokenY) : (tokenY, tokenX);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../lib/math/Math.sol";
import "../lib/helpers/BalancerErrors.sol";
import "../lib/openzeppelin/IERC20.sol";
import "../lib/helpers/AssetHelpers.sol";
import "../lib/openzeppelin/SafeERC20.sol";
import "../lib/openzeppelin/Address.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IAsset.sol";
import "./interfaces/IVault.sol";
abstract contract AssetTransfersHandler is AssetHelpers {
using SafeERC20 for IERC20;
using Address for address payable;
/**
* @dev Receives `amount` of `asset` from `sender`. If `fromInternalBalance` is true, it first withdraws as much
* as possible from Internal Balance, then transfers any remaining amount.
*
* If `asset` is ETH, `fromInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* will be wrapped into WETH.
*
* WARNING: this function does not check that the contract caller has actually supplied any ETH - it is up to the
* caller of this function to check that this is true to prevent the Vault from using its own ETH (though the Vault
* typically doesn't hold any).
*/
function _receiveAsset(
IAsset asset,
uint256 amount,
address sender,
bool fromInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
_require(!fromInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// The ETH amount to receive is deposited into the WETH contract, which will in turn mint WETH for
// the Vault at a 1:1 ratio.
// A check for this condition is also introduced by the compiler, but this one provides a revert reason.
// Note we're checking for the Vault's total balance, *not* ETH sent in this transaction.
_require(address(this).balance >= amount, Errors.INSUFFICIENT_ETH);
_WETH().deposit{ value: amount }();
} else {
IERC20 token = _asIERC20(asset);
if (fromInternalBalance) {
// We take as many tokens from Internal Balance as possible: any remaining amounts will be transferred.
uint256 deductedBalance = _decreaseInternalBalance(sender, token, amount, true);
// Because `deductedBalance` will be always the lesser of the current internal balance
// and the amount to decrease, it is safe to perform unchecked arithmetic.
amount -= deductedBalance;
}
if (amount > 0) {
token.safeTransferFrom(sender, address(this), amount);
}
}
}
/**
* @dev Sends `amount` of `asset` to `recipient`. If `toInternalBalance` is true, the asset is deposited as Internal
* Balance instead of being transferred.
*
* If `asset` is ETH, `toInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds
* are instead sent directly after unwrapping WETH.
*/
function _sendAsset(
IAsset asset,
uint256 amount,
address payable recipient,
bool toInternalBalance
) internal {
if (amount == 0) {
return;
}
if (_isETH(asset)) {
// Sending ETH is not as involved as receiving it: the only special behavior is it cannot be
// deposited to Internal Balance.
_require(!toInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE);
// First, the Vault withdraws deposited ETH from the WETH contract, by burning the same amount of WETH
// from the Vault. This receipt will be handled by the Vault's `receive`.
_WETH().withdraw(amount);
// Then, the withdrawn ETH is sent to the recipient.
recipient.sendValue(amount);
} else {
IERC20 token = _asIERC20(asset);
if (toInternalBalance) {
_increaseInternalBalance(recipient, token, amount);
} else {
token.safeTransfer(recipient, amount);
}
}
}
/**
* @dev Returns excess ETH back to the contract caller, assuming `amountUsed` has been spent. Reverts
* if the caller sent less ETH than `amountUsed`.
*
* Because the caller might not know exactly how much ETH a Vault action will require, they may send extra.
* Note that this excess value is returned *to the contract caller* (msg.sender). If caller and e.g. swap sender are
* not the same (because the caller is a relayer for the sender), then it is up to the caller to manage this
* returned ETH.
*/
function _handleRemainingEth(uint256 amountUsed) internal {
_require(msg.value >= amountUsed, Errors.INSUFFICIENT_ETH);
uint256 excess = msg.value - amountUsed;
if (excess > 0) {
msg.sender.sendValue(excess);
}
}
/**
* @dev Enables the Vault to receive ETH. This is required for it to be able to unwrap WETH, which sends ETH to the
* caller.
*
* Any ETH sent to the Vault outside of the WETH unwrapping mechanism would be forever locked inside the Vault, so
* we prevent that from happening. Other mechanisms used to send ETH to the Vault (such as being the recipient of an
* ETH swap, Pool exit or withdrawal, contract self-destruction, or receiving the block mining reward) will result
* in locked funds, but are not otherwise a security or soundness issue. This check only exists as an attempt to
* prevent user error.
*/
receive() external payable {
_require(msg.sender == address(_WETH()), Errors.ETH_TRANSFER);
}
// This contract uses virtual internal functions instead of inheriting from the modules that implement them (in
// this case UserBalance) in order to decouple it from the rest of the system and enable standalone testing by
// implementing these with mocks.
function _increaseInternalBalance(
address account,
IERC20 token,
uint256 amount
) internal virtual;
function _decreaseInternalBalance(
address account,
IERC20 token,
uint256 amount,
bool capped
) internal virtual returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.0;
import "../openzeppelin/IERC20.sol";
import "../../vault/interfaces/IAsset.sol";
import "../../vault/interfaces/IWETH.sol";
abstract contract AssetHelpers {
// solhint-disable-next-line var-name-mixedcase
IWETH private immutable _weth;
// Sentinel value used to indicate WETH with wrapping/unwrapping semantics. The zero address is a good choice for
// multiple reasons: it is cheap to pass as a calldata argument, it is a known invalid token and non-contract, and
// it is an address Pools cannot register as a token.
address private constant _ETH = address(0);
constructor(IWETH weth) {
_weth = weth;
}
// solhint-disable-next-line func-name-mixedcase
function _WETH() internal view returns (IWETH) {
return _weth;
}
/**
* @dev Returns true if `asset` is the sentinel value that represents ETH.
*/
function _isETH(IAsset asset) internal pure returns (bool) {
return address(asset) == _ETH;
}
/**
* @dev Translates `asset` into an equivalent IERC20 token address. If `asset` represents ETH, it will be translated
* to the WETH contract.
*/
function _translateToIERC20(IAsset asset) internal view returns (IERC20) {
return _isETH(asset) ? _WETH() : _asIERC20(asset);
}
/**
* @dev Same as `_translateToIERC20(IAsset)`, but for an entire array.
*/
function _translateToIERC20(IAsset[] memory assets) internal view returns (IERC20[] memory) {
IERC20[] memory tokens = new IERC20[](assets.length);
for (uint256 i = 0; i < assets.length; ++i) {
tokens[i] = _translateToIERC20(assets[i]);
}
return tokens;
}
/**
* @dev Interprets `asset` as an IERC20 token. This function should only be called on `asset` if `_isETH` previously
* returned false for it, that is, if `asset` is guaranteed not to be the ETH sentinel value.
*/
function _asIERC20(IAsset asset) internal pure returns (IERC20) {
return IERC20(address(asset));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
_require(address(this).balance >= amount, Errors.ADDRESS_INSUFFICIENT_BALANCE);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
_require(success, Errors.ADDRESS_CANNOT_SEND_VALUE);
}
}
| * @dev Transforms `amount` of `token`'s balance in a Two Token Pool from cash into managed. This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is registered for that Pool./ | function _twoTokenPoolCashToManaged(
bytes32 poolId,
IERC20 token,
uint256 amount
) internal {
_updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.cashToManaged, amount);
}
| 642,323 | [
1,
15236,
1375,
8949,
68,
434,
1375,
2316,
11294,
87,
11013,
316,
279,
16896,
3155,
8828,
628,
276,
961,
1368,
7016,
18,
1220,
445,
13041,
1375,
6011,
548,
68,
1704,
16,
13955,
358,
326,
16896,
3155,
4582,
1588,
3637,
16,
471,
716,
1375,
2316,
68,
353,
4104,
364,
716,
8828,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
15415,
1345,
2864,
39,
961,
774,
10055,
12,
203,
3639,
1731,
1578,
2845,
548,
16,
203,
3639,
467,
654,
39,
3462,
1147,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
288,
203,
3639,
389,
2725,
11710,
1345,
2864,
7887,
13937,
12,
6011,
548,
16,
1147,
16,
30918,
17353,
18,
71,
961,
774,
10055,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// contracts/MyNFT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
interface ERC721TokenReceiver
{
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
// look into this
contract Squish is IERC721 {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
event Mint(uint indexed index, address indexed minter);
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
event ApprovalForAll(address owner,address operator,bool approved);
event MultiMint(string handle, uint number);
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
uint public constant TOKEN_LIMIT = 10000;
uint public MINTED_AMOUNT;
uint public squishRemaining = 10000;
uint internal numTokens = 0;
address payable internal deployer;
address payable internal beneficiary;
mapping(bytes4 => bool) internal supportedInterfaces;
//don't think we need this
mapping(uint256 => address) internal idToOwner;
mapping(uint256 => uint256) public creatorNftMints;
mapping(uint256 => address) internal idToApproval;
mapping(address => mapping(address => bool)) internal ownerToOperators;
mapping(address=>uint256[]) internal ownerToIds;
mapping(uint256 => uint256) internal idToOwnerIndex;
string internal nftName = "Squishy";
string internal nftSymbol = "SQSH";
uint internal nonce = 0;
uint[TOKEN_LIMIT] internal indices;
bool private reentrancyLock = false;
modifier onlyDeployer() {
require(msg.sender == deployer, "Only deployer.");
_;
}
/* Prevent a contract function from being reentrant-called. */
modifier reentrancyGuard {
if (reentrancyLock) {
revert();
}
reentrancyLock = true;
_;
reentrancyLock = false;
}
modifier canOperate(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], "Cannot operate.");
_;
}
modifier canTransfer(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| idToApproval[_tokenId] == msg.sender
|| ownerToOperators[tokenOwner][msg.sender], "Cannot transfer."
);
_;
}
//between 0 and the length of the ipfshash array
modifier validNFToken(uint256 _tokenId) {
require(idToOwner[_tokenId] != address(0), "Invalid token.");
_;
}
constructor(address payable _beneficiary) public {
supportedInterfaces[0x01ffc9a7] = true; // ERC165
supportedInterfaces[0x80ac58cd] = true; // ERC721
supportedInterfaces[0x780e9d63] = true; // ERC721 Enumerable
supportedInterfaces[0x5b5e139f] = true; // ERC721 Metadata
deployer = msg.sender;
beneficiary = _beneficiary;
}
//////////////////////////
//// ERC 721 ERC 165 ////
/////////////////////////
function isContract(address _addr) internal view returns (bool addressCheck) {
uint256 size;
assembly { size := extcodesize(_addr) } // solhint-disable-line
addressCheck = size > 0;
}
function supportsInterface(bytes4 _interfaceID) external view override returns (bool) {
return supportedInterfaces[_interfaceID];
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) external override {
_safeTransferFrom(_from, _to, _tokenId, _data);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
_safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom(address _from, address _to, uint256 _tokenId) external override canTransfer(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Wrong from address.");
require(_to != address(0), "Cannot send to 0x0.");
_transfer(_to, _tokenId);
}
function approve(address _approved, uint256 _tokenId) external override canOperate(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) external override {
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function balanceOf(address _owner) external view override returns (uint256) {
require(_owner != address(0));
return _getOwnerNFTCount(_owner);
}
function ownerOf(uint256 _tokenId) external view override returns (address _owner) {
require(idToOwner[_tokenId] != address(0));
_owner = idToOwner[_tokenId];
}
function getApproved(uint256 _tokenId) external view override validNFToken(_tokenId) returns (address) {
return idToApproval[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external override view returns (bool) {
return ownerToOperators[_owner][_operator];
}
function _transfer(address _to, uint256 _tokenId) internal {
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
//// Enumerable
function totalSupply() public view returns (uint256) {
return numTokens;
}
function tokenByIndex(uint256 index) public pure returns (uint256) {
require(index >= 0 && index < TOKEN_LIMIT);
return index + 1;
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_index < ownerToIds[_owner].length);
return ownerToIds[_owner][_index];
}
//// Metadata
function randomIndex() internal returns (uint) {
uint totalSize = TOKEN_LIMIT - numTokens;
uint index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
require(index >= 0, "must have int as index");
uint value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
// Move last value to selected position
if (indices[totalSize - 1] == 0) {
// Array position not initialized, so use position
indices[index] = totalSize - 1;
} else {
// Array position holds a value so use that
indices[index] = indices[totalSize - 1];
}
nonce++;
// Don't allow a zero index, start counting at 1
return value + 1;
}
function multiMint(uint amount) external payable reentrancyGuard returns (uint[] memory) {
require(amount <= 40, "can only mint 10 at a time!");
uint salePrice = amount * (5*10**16 wei);
require(msg.value == salePrice, "insufficient funds to purchase.");
require(numTokens < TOKEN_LIMIT, "Sale limit reached!");
beneficiary.transfer(msg.value);
uint[] memory ids = new uint[](amount);
for (uint8 i=0; i<amount; i++) {
uint id = _mint(msg.sender);
ids[i] = id;
}
return ids;
}
function devMint(address _to) public {
require(msg.sender == deployer, "must be deployer");
uint16[20] memory ids = [6593,734,2445,9836,8097,5697,4700,4440,3277,6084,6311,7883,9610,2971,2253,7129,6057,98,437,14];
for (uint8 i=0; i<ids.length; i++) {
_addNFToken(_to, ids[i]);
numTokens = numTokens + 1;
squishRemaining--;
emit Mint(ids[i], _to);
emit Transfer(address(0), _to, ids[i]);
}
}
function _mint(address _to) internal returns (uint) {
require(_to != address(0), "cannot mint to 0x0");
require(numTokens < TOKEN_LIMIT, "Token limit reached");
uint id = randomIndex();
numTokens = numTokens + 1;
squishRemaining--;
_addNFToken(_to, id);
emit Mint(id, _to);
emit Transfer(address(0), _to, id);
return id;
}
function _addNFToken(address _to, uint256 _tokenId) internal {
require(idToOwner[_tokenId] == address(0), "Cannot add, already owned.");
idToOwner[_tokenId] = _to;
ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1;
}
function _removeNFToken(address _from, uint256 _tokenId) internal {
require(idToOwner[_tokenId] == _from, "Incorrect owner.");
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex) {
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
function _getOwnerNFTCount(address _owner) internal view returns (uint256) {
return ownerToIds[_owner].length;
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private canTransfer(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Incorrect owner.");
require(_to != address(0));
_transfer(_to, _tokenId);
if (isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
function _clearApproval(uint256 _tokenId) private {
if (idToApproval[_tokenId] != address(0)) {
delete idToApproval[_tokenId];
}
}
/**
* @dev Returns a descriptive name for a collection of NFTokens.
* @return _name Representing name.
*/
function name() external view returns (string memory _name) {
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTokens.
* @return _symbol Representing symbol.
*/
function symbol() external view returns (string memory _symbol) {
_symbol = nftSymbol;
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
// remember to put the bytes32 to string back
function tokenURI(uint256 _tokenId) external view validNFToken(_tokenId) returns (string memory) {
return string(abi.encodePacked("ipfs://QmRMn95jNjMpKXTyGpKZ4YojXnpRqZZaD3KMTeUu1CTJPk/",toString(_tokenId),".json"));
}
}
| look into thisdon't think we need this | contract Squish is IERC721 {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
event Mint(uint indexed index, address indexed minter);
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
event ApprovalForAll(address owner,address operator,bool approved);
event MultiMint(string handle, uint number);
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
uint public constant TOKEN_LIMIT = 10000;
uint public MINTED_AMOUNT;
uint public squishRemaining = 10000;
uint internal numTokens = 0;
address payable internal deployer;
address payable internal beneficiary;
mapping(bytes4 => bool) internal supportedInterfaces;
mapping(uint256 => address) internal idToOwner;
mapping(uint256 => uint256) public creatorNftMints;
mapping(uint256 => address) internal idToApproval;
mapping(address => mapping(address => bool)) internal ownerToOperators;
mapping(address=>uint256[]) internal ownerToIds;
mapping(uint256 => uint256) internal idToOwnerIndex;
string internal nftName = "Squishy";
string internal nftSymbol = "SQSH";
uint internal nonce = 0;
uint[TOKEN_LIMIT] internal indices;
bool private reentrancyLock = false;
modifier onlyDeployer() {
require(msg.sender == deployer, "Only deployer.");
_;
}
modifier reentrancyGuard {
if (reentrancyLock) {
revert();
}
reentrancyLock = true;
_;
reentrancyLock = false;
}
modifier reentrancyGuard {
if (reentrancyLock) {
revert();
}
reentrancyLock = true;
_;
reentrancyLock = false;
}
modifier canOperate(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], "Cannot operate.");
_;
}
modifier canTransfer(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| idToApproval[_tokenId] == msg.sender
|| ownerToOperators[tokenOwner][msg.sender], "Cannot transfer."
);
_;
}
modifier validNFToken(uint256 _tokenId) {
require(idToOwner[_tokenId] != address(0), "Invalid token.");
_;
}
constructor(address payable _beneficiary) public {
deployer = msg.sender;
beneficiary = _beneficiary;
}
function isContract(address _addr) internal view returns (bool addressCheck) {
uint256 size;
addressCheck = size > 0;
}
function supportsInterface(bytes4 _interfaceID) external view override returns (bool) {
return supportedInterfaces[_interfaceID];
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) external override {
_safeTransferFrom(_from, _to, _tokenId, _data);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
_safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom(address _from, address _to, uint256 _tokenId) external override canTransfer(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Wrong from address.");
require(_to != address(0), "Cannot send to 0x0.");
_transfer(_to, _tokenId);
}
function approve(address _approved, uint256 _tokenId) external override canOperate(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) external override {
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function balanceOf(address _owner) external view override returns (uint256) {
require(_owner != address(0));
return _getOwnerNFTCount(_owner);
}
function ownerOf(uint256 _tokenId) external view override returns (address _owner) {
require(idToOwner[_tokenId] != address(0));
_owner = idToOwner[_tokenId];
}
function getApproved(uint256 _tokenId) external view override validNFToken(_tokenId) returns (address) {
return idToApproval[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external override view returns (bool) {
return ownerToOperators[_owner][_operator];
}
function _transfer(address _to, uint256 _tokenId) internal {
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
function totalSupply() public view returns (uint256) {
return numTokens;
}
function tokenByIndex(uint256 index) public pure returns (uint256) {
require(index >= 0 && index < TOKEN_LIMIT);
return index + 1;
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_index < ownerToIds[_owner].length);
return ownerToIds[_owner][_index];
}
function randomIndex() internal returns (uint) {
uint totalSize = TOKEN_LIMIT - numTokens;
uint index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
require(index >= 0, "must have int as index");
uint value = 0;
if (indices[index] != 0) {
value = indices[index];
value = index;
}
if (indices[totalSize - 1] == 0) {
indices[index] = totalSize - 1;
indices[index] = indices[totalSize - 1];
}
nonce++;
}
function randomIndex() internal returns (uint) {
uint totalSize = TOKEN_LIMIT - numTokens;
uint index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
require(index >= 0, "must have int as index");
uint value = 0;
if (indices[index] != 0) {
value = indices[index];
value = index;
}
if (indices[totalSize - 1] == 0) {
indices[index] = totalSize - 1;
indices[index] = indices[totalSize - 1];
}
nonce++;
}
} else {
function randomIndex() internal returns (uint) {
uint totalSize = TOKEN_LIMIT - numTokens;
uint index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
require(index >= 0, "must have int as index");
uint value = 0;
if (indices[index] != 0) {
value = indices[index];
value = index;
}
if (indices[totalSize - 1] == 0) {
indices[index] = totalSize - 1;
indices[index] = indices[totalSize - 1];
}
nonce++;
}
} else {
return value + 1;
function multiMint(uint amount) external payable reentrancyGuard returns (uint[] memory) {
require(amount <= 40, "can only mint 10 at a time!");
uint salePrice = amount * (5*10**16 wei);
require(msg.value == salePrice, "insufficient funds to purchase.");
require(numTokens < TOKEN_LIMIT, "Sale limit reached!");
beneficiary.transfer(msg.value);
uint[] memory ids = new uint[](amount);
for (uint8 i=0; i<amount; i++) {
uint id = _mint(msg.sender);
ids[i] = id;
}
return ids;
}
function multiMint(uint amount) external payable reentrancyGuard returns (uint[] memory) {
require(amount <= 40, "can only mint 10 at a time!");
uint salePrice = amount * (5*10**16 wei);
require(msg.value == salePrice, "insufficient funds to purchase.");
require(numTokens < TOKEN_LIMIT, "Sale limit reached!");
beneficiary.transfer(msg.value);
uint[] memory ids = new uint[](amount);
for (uint8 i=0; i<amount; i++) {
uint id = _mint(msg.sender);
ids[i] = id;
}
return ids;
}
function devMint(address _to) public {
require(msg.sender == deployer, "must be deployer");
uint16[20] memory ids = [6593,734,2445,9836,8097,5697,4700,4440,3277,6084,6311,7883,9610,2971,2253,7129,6057,98,437,14];
for (uint8 i=0; i<ids.length; i++) {
_addNFToken(_to, ids[i]);
numTokens = numTokens + 1;
squishRemaining--;
emit Mint(ids[i], _to);
emit Transfer(address(0), _to, ids[i]);
}
}
function devMint(address _to) public {
require(msg.sender == deployer, "must be deployer");
uint16[20] memory ids = [6593,734,2445,9836,8097,5697,4700,4440,3277,6084,6311,7883,9610,2971,2253,7129,6057,98,437,14];
for (uint8 i=0; i<ids.length; i++) {
_addNFToken(_to, ids[i]);
numTokens = numTokens + 1;
squishRemaining--;
emit Mint(ids[i], _to);
emit Transfer(address(0), _to, ids[i]);
}
}
function _mint(address _to) internal returns (uint) {
require(_to != address(0), "cannot mint to 0x0");
require(numTokens < TOKEN_LIMIT, "Token limit reached");
uint id = randomIndex();
numTokens = numTokens + 1;
squishRemaining--;
_addNFToken(_to, id);
emit Mint(id, _to);
emit Transfer(address(0), _to, id);
return id;
}
function _addNFToken(address _to, uint256 _tokenId) internal {
require(idToOwner[_tokenId] == address(0), "Cannot add, already owned.");
idToOwner[_tokenId] = _to;
ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1;
}
function _removeNFToken(address _from, uint256 _tokenId) internal {
require(idToOwner[_tokenId] == _from, "Incorrect owner.");
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex) {
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
function _removeNFToken(address _from, uint256 _tokenId) internal {
require(idToOwner[_tokenId] == _from, "Incorrect owner.");
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex) {
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
function _getOwnerNFTCount(address _owner) internal view returns (uint256) {
return ownerToIds[_owner].length;
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private canTransfer(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Incorrect owner.");
require(_to != address(0));
_transfer(_to, _tokenId);
if (isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private canTransfer(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Incorrect owner.");
require(_to != address(0));
_transfer(_to, _tokenId);
if (isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
function _clearApproval(uint256 _tokenId) private {
if (idToApproval[_tokenId] != address(0)) {
delete idToApproval[_tokenId];
}
}
function _clearApproval(uint256 _tokenId) private {
if (idToApproval[_tokenId] != address(0)) {
delete idToApproval[_tokenId];
}
}
function name() external view returns (string memory _name) {
_name = nftName;
}
function symbol() external view returns (string memory _symbol) {
_symbol = nftSymbol;
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
function tokenURI(uint256 _tokenId) external view validNFToken(_tokenId) returns (string memory) {
}
}
| 513,430 | [
1,
7330,
1368,
333,
19752,
1404,
15507,
732,
1608,
333,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
348,
372,
1468,
353,
467,
654,
39,
27,
5340,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
2673,
31,
203,
203,
565,
871,
490,
474,
12,
11890,
8808,
770,
16,
1758,
8808,
1131,
387,
1769,
203,
203,
565,
871,
12279,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
3410,
16,
1758,
20412,
16,
2254,
5034,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
2867,
3410,
16,
2867,
3726,
16,
6430,
20412,
1769,
203,
203,
565,
871,
5991,
49,
474,
12,
1080,
1640,
16,
2254,
1300,
1769,
203,
203,
565,
1731,
24,
2713,
5381,
490,
22247,
67,
673,
67,
654,
39,
27,
5340,
67,
27086,
20764,
273,
374,
92,
23014,
70,
27,
69,
3103,
31,
203,
203,
565,
2254,
1071,
5381,
14275,
67,
8283,
273,
12619,
31,
203,
565,
2254,
1071,
6989,
6404,
67,
2192,
51,
5321,
31,
203,
565,
2254,
1071,
17715,
1468,
11429,
273,
12619,
31,
203,
565,
2254,
2713,
818,
5157,
273,
374,
31,
203,
203,
565,
1758,
8843,
429,
2713,
7286,
264,
31,
203,
565,
1758,
8843,
429,
2713,
27641,
74,
14463,
814,
31,
203,
203,
565,
2874,
12,
3890,
24,
516,
1426,
13,
2713,
3260,
10273,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
2713,
612,
774,
5541,
31,
203,
203,
565,
2874,
12,
11890,
5034,
2
]
|
./partial_match/5/0x6a82A2128F382d09aB36D7076bdB871eF879a9cE/sources/contracts/MarketPlace.sol | * @notice set a new marketplace fees (scaled by 1000000) (onlyOwner) @param _newMPFees new marketplace fees/ | function setMarketPlaceFee(uint256 _newMPFees) external onlyOwner {
marketPlaceFees = _newMPFees;
}
| 16,858,174 | [
1,
542,
279,
394,
29917,
1656,
281,
261,
20665,
635,
15088,
13,
261,
3700,
5541,
13,
225,
389,
2704,
4566,
2954,
281,
394,
29917,
1656,
281,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
3882,
278,
6029,
14667,
12,
11890,
5034,
389,
2704,
4566,
2954,
281,
13,
3903,
1338,
5541,
288,
203,
3639,
13667,
6029,
2954,
281,
273,
389,
2704,
4566,
2954,
281,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.19;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract JouleAPI {
event Invoked(address indexed _invoker, address indexed _address, bool _status, uint _usedGas);
event Registered(address indexed _registrant, address indexed _address, uint _timestamp, uint _gasLimit, uint _gasPrice);
event Unregistered(address indexed _registrant, address indexed _address, uint _timestamp, uint _gasLimit, uint _gasPrice, uint _amount);
/**
* @dev Registers the specified contract to invoke at the specified time with the specified gas and price.
* @notice Registration requires the specified amount of ETH in value, to cover invoke bonus. See getPrice method.
*
* @param _address Contract's address. Contract MUST implements Checkable interface.
* @param _timestamp Timestamp at what moment contract should be called. It MUST be in future.
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
* @return Amount of change.
*/
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint);
/**
* @dev Registers the specified contract to invoke at the specified time with the specified gas and price.
* @notice Registration requires the specified amount of ETH in value, to cover invoke bonus. See getPrice method.
* @notice If value would be more then required (see getPrice) change will be returned to msg.sender (not to _registrant!).
*
* @param _registrant Any address which will be owners for this registration. Only he can unregister. Useful for calling from contract.
* @param _address Contract's address. Contract MUST implements Checkable interface.
* @param _timestamp Timestamp at what moment contract should be called. It MUST be in future.
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
* @return Amount of change.
*/
function registerFor(address _registrant, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public payable returns (uint);
/**
* @dev Remove registration of the specified contract (with exact parameters) by the specified key. See findKey method for looking for key.
* @notice It returns not full amount of ETH.
* @notice Only registrant can remove their registration.
* @notice Only registrations in future can be removed.
*
* @param _key Contract key, to fast finding during unregister. See findKey method for getting key.
* @param _address Contract's address. Contract MUST implements Checkable interface.
* @param _timestamp Timestamp at what moment contract should be called. It MUST be in future.
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
* @return Amount of refund.
*/
function unregister(bytes32 _key, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external returns (uint);
/**
* @dev Invokes next contracts in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @return Reward amount.
*/
function invoke() public returns (uint);
/**
* @dev Invokes next contracts in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @param _invoker Any address from which event will be threw. Useful for calling from contract.
* @return Reward amount.
*/
function invokeFor(address _invoker) public returns (uint);
/**
* @dev Invokes the top contract in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @return Reward amount.
*/
function invokeOnce() public returns (uint);
/**
* @dev Invokes the top contract in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @param _invoker Any address from which event will be threw. Useful for calling from contract.
* @return Reward amount.
*/
function invokeOnceFor(address _invoker) public returns (uint);
/**
* @dev Calculates required to register amount of WEI.
*
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
* @return Amount in wei.
*/
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint);
/**
* @dev Gets how many contracts are registered (and not invoked).
*/
function getCount() public view returns (uint);
/**
* @dev Gets top contract (the next to invoke).
*
* @return contractAddress The contract address.
* @return timestamp The invocation timestamp.
* @return gasLimit The contract gas.
* @return gasPrice The invocation expected price.
* @return invokeGas The minimal amount of gas to invoke (including gas for joule).
* @return rewardAmount The amount of reward for invocation.
*/
function getTopOnce() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice,
uint invokeGas,
uint rewardAmount
);
/**
* @dev Gets one next contract by the specified previous in order to invoke.
*
* @param _contractAddress The previous contract address.
* @param _timestamp The previous invocation timestamp.
* @param _gasLimit The previous invocation maximum gas.
* @param _gasPrice The previous invocation expected price.
* @return contractAddress The contract address.
* @return gasLimit The contract gas.
* @return gasPrice The invocation expected price.
* @return invokeGas The minimal amount of gas to invoke (including gas for joule).
* @return rewardAmount The amount of reward for invocation.
*/
function getNextOnce(address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) public view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice,
uint invokeGas,
uint rewardAmount
);
/**
* @dev Gets _count next contracts by the specified previous in order to invoke.
* @notice Unlike getTop this method return exact _count values.
*
* @param _count The count of result contracts.
* @param _contractAddress The previous contract address.
* @param _timestamp The previous invocation timestamp.
* @param _gasLimit The previous invocation maximum gas.
* @param _gasPrice The previous invocation expected price.
* @return contractAddress The contract address.
* @return gasLimit The contract gas.
* @return gasPrice The invocation expected price.
* @return invokeGas The minimal amount of gas to invoke (including gas for joule).
* @return rewardAmount The amount of reward for invocation.
*/
function getNext(uint _count,
address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) external view returns (
address[] addresses,
uint[] timestamps,
uint[] gasLimits,
uint[] gasPrices,
uint[] invokeGases,
uint[] rewardAmounts
);
/**
* @dev Gets top _count contracts (in order to invoke).
*
* @param _count How many records will be returned.
* @return addresses The contracts addresses.
* @return timestamps The invocation timestamps.
* @return gasLimits The contract gas.
* @return gasPrices The invocation expected price.
* @return invokeGases The minimal amount of gas to invoke (including gas for joule).
* @return rewardAmounts The amount of reward for invocation.
*/
function getTop(uint _count) external view returns (
address[] addresses,
uint[] timestamps,
uint[] gasLimits,
uint[] gasPrices,
uint[] invokeGases,
uint[] rewardAmounts
);
/**
* @dev Finds key for the registration with exact parameters. Be careful, key might be changed because of other registrations.
* @param _address Contract's address. Contract MUST implements Checkable interface.
* @param _timestamp Timestamp at what moment contract should be called. It MUST be in future.
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
* @return _key Key of the specified registration.
*/
function findKey(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public view returns (bytes32);
/**
* @dev Gets actual code version.
* @return Code version. Mask: 0xff.0xff.0xffff-0xffffffff (major.minor.build-hash)
*/
function getVersion() external view returns (bytes8);
/**
* @dev Gets minimal gas price, specified by maintainer.
*/
function getMinGasPrice() public view returns (uint);
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract TransferToken is Ownable {
function transferToken(ERC20Basic _token, address _to, uint _value) public onlyOwner {
_token.transfer(_to, _value);
}
}
contract JouleProxyAPI {
/**
* Function hash is: 0x73027f6d
*/
function callback(address _invoker, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public returns (bool);
}
contract CheckableContract {
event Checked();
/*
* Function hash is 0x919840ad.
*/
function check() public;
}
contract usingConsts {
uint constant GWEI = 0.001 szabo;
// this values influence to the reward price! do not change for already registered contracts!
uint constant TRANSACTION_GAS = 22000;
// remaining gas - amount of gas to finish transaction after invoke
uint constant REMAINING_GAS = 30000;
// joule gas - gas to joule (including proxy and others) invocation, excluding contract gas
uint constant JOULE_GAS = TRANSACTION_GAS + REMAINING_GAS + 5000;
// minimal default gas price (because of network load)
uint32 constant DEFAULT_MIN_GAS_PRICE_GWEI = 20;
// min gas price
uint constant MIN_GAS_PRICE = GWEI;
// max gas price
uint constant MAX_GAS_PRICE = 0xffffffff * GWEI;
// not, it mist be less then 0x00ffffff, because high bytes might be used for storing flags
uint constant MAX_GAS = 4000000;
// Code version
bytes8 constant VERSION = 0x0108000000000000;
// ^^ - major
// ^^ - minor
// ^^^^ - build
// ^^^^^^^^ - git hash
}
library KeysUtils {
// Such order is important to load from state
struct Object {
uint32 gasPriceGwei;
uint32 gasLimit;
uint32 timestamp;
address contractAddress;
}
function toKey(Object _obj) internal pure returns (bytes32) {
return toKey(_obj.contractAddress, _obj.timestamp, _obj.gasLimit, _obj.gasPriceGwei);
}
function toKeyFromStorage(Object storage _obj) internal view returns (bytes32 _key) {
assembly {
_key := sload(_obj_slot)
}
}
function toKey(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal pure returns (bytes32 result) {
result = 0x0000000000000000000000000000000000000000000000000000000000000000;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - address (20 bytes)
// ^^^^^^^^ - timestamp (4 bytes)
// ^^^^^^^^ - gas limit (4 bytes)
// ^^^^^^^^ - gas price (4 bytes)
assembly {
result := or(result, mul(_address, 0x1000000000000000000000000))
result := or(result, mul(and(_timestamp, 0xffffffff), 0x10000000000000000))
result := or(result, mul(and(_gasLimit, 0xffffffff), 0x100000000))
result := or(result, and(_gasPrice, 0xffffffff))
}
}
function toMemoryObject(bytes32 _key, Object memory _dest) internal pure {
assembly {
mstore(_dest, and(_key, 0xffffffff))
mstore(add(_dest, 0x20), and(div(_key, 0x100000000), 0xffffffff))
mstore(add(_dest, 0x40), and(div(_key, 0x10000000000000000), 0xffffffff))
mstore(add(_dest, 0x60), div(_key, 0x1000000000000000000000000))
}
}
function toObject(bytes32 _key) internal pure returns (Object memory _dest) {
toMemoryObject(_key, _dest);
}
function toStateObject(bytes32 _key, Object storage _dest) internal {
assembly {
sstore(_dest_slot, _key)
}
}
function getTimestamp(bytes32 _key) internal pure returns (uint result) {
assembly {
result := and(div(_key, 0x10000000000000000), 0xffffffff)
}
}
}
contract Restriction {
mapping (address => bool) internal accesses;
function Restriction() public {
accesses[msg.sender] = true;
}
function giveAccess(address _addr) public restricted {
accesses[_addr] = true;
}
function removeAccess(address _addr) public restricted {
delete accesses[_addr];
}
function hasAccess() public constant returns (bool) {
return accesses[msg.sender];
}
modifier restricted() {
require(hasAccess());
_;
}
}
contract JouleStorage is Restriction {
mapping(bytes32 => bytes32) map;
function get(bytes32 _key) public view returns (bytes32 _value) {
return map[_key];
}
function set(bytes32 _key, bytes32 _value) public restricted {
map[_key] = _value;
}
function del(bytes32 _key) public restricted {
delete map[_key];
}
function getAndDel(bytes32 _key) public restricted returns (bytes32 _value) {
_value = map[_key];
delete map[_key];
}
function swap(bytes32 _from, bytes32 _to) public restricted returns (bytes32 _value) {
_value = map[_to];
map[_to] = map[_from];
delete map[_from];
}
}
contract JouleIndexCore {
using KeysUtils for bytes32;
uint constant YEAR = 0x1DFE200;
bytes32 constant HEAD = 0x0;
// YEAR -> week -> hour -> minute
JouleStorage public state;
function JouleIndexCore(JouleStorage _storage) public {
state = _storage;
}
function insertIndex(bytes32 _key) internal {
uint timestamp = _key.getTimestamp();
bytes32 year = toKey(timestamp, YEAR);
bytes32 headLow;
bytes32 headHigh;
(headLow, headHigh) = fromValue(state.get(HEAD));
if (year < headLow || headLow == 0 || year > headHigh) {
if (year < headLow || headLow == 0) {
headLow = year;
}
if (year > headHigh) {
headHigh = year;
}
state.set(HEAD, toValue(headLow, headHigh));
}
bytes32 week = toKey(timestamp, 1 weeks);
bytes32 low;
bytes32 high;
(low, high) = fromValue(state.get(year));
if (week < low || week > high) {
if (week < low || low == 0) {
low = week;
}
if (week > high) {
high = week;
}
state.set(year, toValue(low, high));
}
(low, high) = fromValue(state.get(week));
bytes32 hour = toKey(timestamp, 1 hours);
if (hour < low || hour > high) {
if (hour < low || low == 0) {
low = hour;
}
if (hour > high) {
high = hour;
}
state.set(week, toValue(low, high));
}
(low, high) = fromValue(state.get(hour));
bytes32 minute = toKey(timestamp, 1 minutes);
if (minute < low || minute > high) {
if (minute < low || low == 0) {
low = minute;
}
if (minute > high) {
high = minute;
}
state.set(hour, toValue(low, high));
}
(low, high) = fromValue(state.get(minute));
bytes32 tsKey = toKey(timestamp);
if (tsKey < low || tsKey > high) {
if (tsKey < low || low == 0) {
low = tsKey;
}
if (tsKey > high) {
high = tsKey;
}
state.set(minute, toValue(low, high));
}
state.set(tsKey, _key);
}
/**
* @dev Update key value from the previous state to new. Timestamp MUST be the same on both keys.
*/
function updateIndex(bytes32 _prev, bytes32 _key) internal {
uint timestamp = _key.getTimestamp();
bytes32 tsKey = toKey(timestamp);
bytes32 prevKey = state.get(tsKey);
// on the same timestamp might be other key, in that case we do not need to update it
if (prevKey != _prev) {
return;
}
state.set(tsKey, _key);
}
function findFloorKeyYear(uint _timestamp, bytes32 _low, bytes32 _high) view private returns (bytes32) {
bytes32 year = toKey(_timestamp, YEAR);
if (year < _low) {
return 0;
}
if (year > _high) {
// week
(low, high) = fromValue(state.get(_high));
// hour
(low, high) = fromValue(state.get(high));
// minute
(low, high) = fromValue(state.get(high));
// ts
(low, high) = fromValue(state.get(high));
return state.get(high);
}
bytes32 low;
bytes32 high;
while (year >= _low) {
(low, high) = fromValue(state.get(year));
if (low != 0) {
bytes32 key = findFloorKeyWeek(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 0x1DFE200 = 52 weeks = 31449600
assembly {
year := sub(year, 0x1DFE200)
}
}
return 0;
}
function findFloorKeyWeek(uint _timestamp, bytes32 _low, bytes32 _high) view private returns (bytes32) {
bytes32 week = toKey(_timestamp, 1 weeks);
if (week < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (week > _high) {
// hour
(low, high) = fromValue(state.get(_high));
// minute
(low, high) = fromValue(state.get(high));
// ts
(low, high) = fromValue(state.get(high));
return state.get(high);
}
while (week >= _low) {
(low, high) = fromValue(state.get(week));
if (low != 0) {
bytes32 key = findFloorKeyHour(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 weeks = 604800
assembly {
week := sub(week, 604800)
}
}
return 0;
}
function findFloorKeyHour(uint _timestamp, bytes32 _low, bytes32 _high) view private returns (bytes32) {
bytes32 hour = toKey(_timestamp, 1 hours);
if (hour < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (hour > _high) {
// minute
(low, high) = fromValue(state.get(_high));
// ts
(low, high) = fromValue(state.get(high));
return state.get(high);
}
while (hour >= _low) {
(low, high) = fromValue(state.get(hour));
if (low != 0) {
bytes32 key = findFloorKeyMinute(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 hours = 3600
assembly {
hour := sub(hour, 3600)
}
}
return 0;
}
function findFloorKeyMinute(uint _timestamp, bytes32 _low, bytes32 _high) view private returns (bytes32) {
bytes32 minute = toKey(_timestamp, 1 minutes);
if (minute < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (minute > _high) {
// ts
(low, high) = fromValue(state.get(_high));
return state.get(high);
}
while (minute >= _low) {
(low, high) = fromValue(state.get(minute));
if (low != 0) {
bytes32 key = findFloorKeyTimestamp(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 minutes = 60
assembly {
minute := sub(minute, 60)
}
}
return 0;
}
function findFloorKeyTimestamp(uint _timestamp, bytes32 _low, bytes32 _high) view private returns (bytes32) {
bytes32 tsKey = toKey(_timestamp);
if (tsKey < _low) {
return 0;
}
if (tsKey > _high) {
return state.get(_high);
}
while (tsKey >= _low) {
bytes32 key = state.get(tsKey);
if (key != 0) {
return key;
}
assembly {
tsKey := sub(tsKey, 1)
}
}
return 0;
}
function findFloorKeyIndex(uint _timestamp) view internal returns (bytes32) {
// require(_timestamp > 0xffffffff);
// if (_timestamp < 1515612415) {
// return 0;
// }
bytes32 yearLow;
bytes32 yearHigh;
(yearLow, yearHigh) = fromValue(state.get(HEAD));
return findFloorKeyYear(_timestamp, yearLow, yearHigh);
}
function toKey(uint _timestamp, uint rounder) pure private returns (bytes32 result) {
// 0x0...00000000000000000
// ^^^^^^^^ - rounder marker (eg, to avoid crossing first day of year with year)
// ^^^^^^^^ - rounded moment (year, week, etc)
assembly {
result := or(mul(rounder, 0x100000000), mul(div(_timestamp, rounder), rounder))
}
}
function toValue(bytes32 _lowKey, bytes32 _highKey) pure private returns (bytes32 result) {
assembly {
result := or(mul(_lowKey, 0x10000000000000000), _highKey)
}
}
function fromValue(bytes32 _value) pure private returns (bytes32 _lowKey, bytes32 _highKey) {
assembly {
_lowKey := and(div(_value, 0x10000000000000000), 0xffffffffffffffff)
_highKey := and(_value, 0xffffffffffffffff)
}
}
function toKey(uint timestamp) pure internal returns (bytes32) {
return bytes32(timestamp);
}
}
contract JouleContractHolder is JouleIndexCore, usingConsts {
using KeysUtils for bytes32;
uint internal length;
bytes32 public head;
function JouleContractHolder(bytes32 _head, uint _length, JouleStorage _storage) public
JouleIndexCore(_storage) {
head = _head;
length = _length;
}
function insert(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal {
length ++;
bytes32 id = KeysUtils.toKey(_address, _timestamp, _gasLimit, _gasPrice);
if (head == 0) {
head = id;
insertIndex(id);
// Found(0xffffffff);
return;
}
bytes32 previous = findFloorKeyIndex(_timestamp);
// reject duplicate key on the end
require(previous != id);
// reject duplicate in the middle
require(state.get(id) == 0);
uint prevTimestamp = previous.getTimestamp();
// Found(prevTimestamp);
uint headTimestamp = head.getTimestamp();
// add as head, prevTimestamp == 0 or in the past
if (prevTimestamp < headTimestamp) {
state.set(id, head);
head = id;
}
// add after the previous
else {
state.set(id, state.get(previous));
state.set(previous, id);
}
insertIndex(id);
}
function updateGas(bytes32 _key, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice, uint _newGasLimit) internal {
bytes32 id = KeysUtils.toKey(_address, _timestamp, _gasLimit, _gasPrice);
bytes32 newId = KeysUtils.toKey(_address, _timestamp, _newGasLimit, _gasPrice);
if (id == head) {
bytes32 afterHead = state.get(id);
head = newId;
state.set(newId, afterHead);
return;
}
require(state.get(_key) == id);
state.set(_key, newId);
state.swap(id, newId);
updateIndex(id, newId);
}
function next() internal {
head = state.getAndDel(head);
length--;
}
function getCount() public view returns (uint) {
return length;
}
function getRecord(bytes32 _parent) internal view returns (bytes32 _record) {
if (_parent == 0) {
_record = head;
}
else {
_record = state.get(_parent);
}
}
/**
* @dev Find previous key for existing value.
*/
function findPrevious(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal view returns (bytes32) {
bytes32 target = KeysUtils.toKey(_address, _timestamp, _gasLimit, _gasPrice);
bytes32 previous = head;
if (target == previous) {
return 0;
}
// if it is not head time
if (_timestamp != previous.getTimestamp()) {
previous = findFloorKeyIndex(_timestamp - 1);
}
bytes32 current = state.get(previous);
while (current != target) {
previous = current;
current = state.get(previous);
}
return previous;
}
}
contract JouleVault is Ownable {
address public joule;
function setJoule(address _joule) public onlyOwner {
joule = _joule;
}
modifier onlyJoule() {
require(msg.sender == address(joule));
_;
}
function withdraw(address _receiver, uint _amount) public onlyJoule {
_receiver.transfer(_amount);
}
function () public payable {
}
}
contract JouleCore is JouleContractHolder {
JouleVault public vault;
uint32 public minGasPriceGwei = DEFAULT_MIN_GAS_PRICE_GWEI;
using KeysUtils for bytes32;
function JouleCore(JouleVault _vault, bytes32 _head, uint _length, JouleStorage _storage) public
JouleContractHolder(_head, _length, _storage) {
vault = _vault;
}
function innerRegister(address _registrant, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal returns (uint) {
uint price = getPriceInner(_gasLimit, _gasPrice);
require(msg.value >= price);
vault.transfer(price);
// this restriction to avoid attack to brake index tree (crossing key)
require(_address != 0);
require(_timestamp > now);
require(_timestamp < 0x100000000);
require(_gasLimit <= MAX_GAS);
require(_gasLimit != 0);
// from 1 gwei to 0x100000000 gwei
require(_gasPrice >= minGasPriceGwei * GWEI);
require(_gasPrice < MAX_GAS_PRICE);
// 0 means not yet registered
require(_registrant != 0x0);
uint innerGasPrice = _gasPrice / GWEI;
insert(_address, _timestamp, _gasLimit, innerGasPrice);
saveRegistrant(_registrant, _address, _timestamp, _gasLimit, innerGasPrice);
if (msg.value > price) {
msg.sender.transfer(msg.value - price);
return msg.value - price;
}
return 0;
}
function saveRegistrant(address _registrant, address _address, uint _timestamp, uint, uint) internal {
bytes32 id = KeysUtils.toKey(_address, _timestamp, 0, 0);
require(state.get(id) == 0);
state.set(id, bytes32(_registrant));
}
function getRegistrant(address _address, uint _timestamp, uint, uint) internal view returns (address) {
bytes32 id = KeysUtils.toKey(_address, _timestamp, 0, 0);
return address(state.get(id));
}
function delRegistrant(KeysUtils.Object memory current) internal {
bytes32 id = KeysUtils.toKey(current.contractAddress, current.timestamp, 0, 0);
state.del(id);
}
function findKey(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public view returns (bytes32) {
require(_address != 0);
require(_timestamp > now);
require(_timestamp < 0x100000000);
require(_gasLimit < MAX_GAS);
require(_gasPrice > GWEI);
require(_gasPrice < 0x100000000 * GWEI);
return findPrevious(_address, _timestamp, _gasLimit, _gasPrice / GWEI);
}
function innerUnregister(address _registrant, bytes32 _key, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal returns (uint) {
// only future registrations might be updated, to avoid race condition in block (with invoke)
require(_timestamp > now);
// to avoid removing already removed keys
require(_gasLimit != 0);
uint innerGasPrice = _gasPrice / GWEI;
// check registrant
address registrant = getRegistrant(_address, _timestamp, _gasLimit, innerGasPrice);
require(registrant == _registrant);
updateGas(_key, _address, _timestamp, _gasLimit, innerGasPrice, 0);
uint amount = _gasLimit * _gasPrice;
if (amount != 0) {
vault.withdraw(registrant, amount);
}
return amount;
}
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint) {
require(_gasLimit <= MAX_GAS);
require(_gasPrice > GWEI);
require(_gasPrice < 0x100000000 * GWEI);
return getPriceInner(_gasLimit, _gasPrice);
}
function getPriceInner(uint _gasLimit, uint _gasPrice) internal pure returns (uint) {
// if this logic will be changed, look also to the innerUnregister method
return (_gasLimit + JOULE_GAS) * _gasPrice;
}
function getVersion() external view returns (bytes8) {
return VERSION;
}
function getTop(uint _count) external view returns (
address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices,
uint[] _invokeGases,
uint[] _rewardAmounts
) {
uint amount = _count <= length ? _count : length;
_addresses = new address[](amount);
_timestamps = new uint[](amount);
_gasLimits = new uint[](amount);
_gasPrices = new uint[](amount);
_invokeGases = new uint[](amount);
_rewardAmounts = new uint[](amount);
bytes32 current = getRecord(0);
for (uint i = 0; i < amount; i ++) {
KeysUtils.Object memory obj = current.toObject();
_addresses[i] = obj.contractAddress;
_timestamps[i] = obj.timestamp;
uint gasLimit = obj.gasLimit;
_gasLimits[i] = gasLimit;
uint gasPrice = obj.gasPriceGwei * GWEI;
_gasPrices[i] = gasPrice;
uint invokeGas = gasLimit + JOULE_GAS;
_invokeGases[i] = invokeGas;
_rewardAmounts[i] = invokeGas * gasPrice;
current = getRecord(current);
}
}
function getTopOnce() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice,
uint invokeGas,
uint rewardAmount
) {
KeysUtils.Object memory obj = getRecord(0).toObject();
contractAddress = obj.contractAddress;
timestamp = obj.timestamp;
gasLimit = obj.gasLimit;
gasPrice = obj.gasPriceGwei * GWEI;
invokeGas = gasLimit + JOULE_GAS;
rewardAmount = invokeGas * gasPrice;
}
function getNextOnce(address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) public view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice,
uint invokeGas,
uint rewardAmount
) {
if (_timestamp == 0) {
return this.getTopOnce();
}
bytes32 prev = KeysUtils.toKey(_contractAddress, _timestamp, _gasLimit, _gasPrice / GWEI);
bytes32 current = getRecord(prev);
KeysUtils.Object memory obj = current.toObject();
contractAddress = obj.contractAddress;
timestamp = obj.timestamp;
gasLimit = obj.gasLimit;
gasPrice = obj.gasPriceGwei * GWEI;
invokeGas = gasLimit + JOULE_GAS;
rewardAmount = invokeGas * gasPrice;
}
function getNext(uint _count,
address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) external view returns (address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices,
uint[] _invokeGases,
uint[] _rewardAmounts) {
_addresses = new address[](_count);
_timestamps = new uint[](_count);
_gasLimits = new uint[](_count);
_gasPrices = new uint[](_count);
_invokeGases = new uint[](_count);
_rewardAmounts = new uint[](_count);
bytes32 prev;
if (_timestamp != 0) {
prev = KeysUtils.toKey(_contractAddress, _timestamp, _gasLimit, _gasPrice / GWEI);
}
uint index = 0;
while (index < _count) {
bytes32 current = getRecord(prev);
if (current == 0) {
break;
}
KeysUtils.Object memory obj = current.toObject();
_addresses[index] = obj.contractAddress;
_timestamps[index] = obj.timestamp;
_gasLimits[index] = obj.gasLimit;
_gasPrices[index] = obj.gasPriceGwei * GWEI;
_invokeGases[index] = obj.gasLimit + JOULE_GAS;
_rewardAmounts[index] = (obj.gasLimit + JOULE_GAS) * obj.gasPriceGwei * GWEI;
prev = current;
index ++;
}
}
function next(KeysUtils.Object memory current) internal {
delRegistrant(current);
next();
}
function innerInvoke(address _invoker) internal returns (uint _amount) {
KeysUtils.Object memory current = KeysUtils.toObject(head);
uint amount;
while (current.timestamp != 0 && current.timestamp < now && msg.gas > (current.gasLimit + REMAINING_GAS)) {
if (current.gasLimit != 0) {
invokeCallback(_invoker, current);
}
amount += getPriceInner(current.gasLimit, current.gasPriceGwei * GWEI);
next(current);
current = head.toObject();
}
if (amount > 0) {
vault.withdraw(msg.sender, amount);
}
return amount;
}
function innerInvokeOnce(address _invoker) internal returns (uint _amount) {
KeysUtils.Object memory current = head.toObject();
next(current);
if (current.gasLimit != 0) {
invokeCallback(_invoker, current);
}
uint amount = getPriceInner(current.gasLimit, current.gasPriceGwei * GWEI);
if (amount > 0) {
vault.withdraw(msg.sender, amount);
}
return amount;
}
function invokeCallback(address, KeysUtils.Object memory _record) internal returns (bool) {
require(msg.gas >= _record.gasLimit);
return _record.contractAddress.call.gas(_record.gasLimit)(0x919840ad);
}
}
contract JouleBehindProxy is JouleCore, Ownable, TransferToken {
JouleProxyAPI public proxy;
function JouleBehindProxy(JouleVault _vault, bytes32 _head, uint _length, JouleStorage _storage) public
JouleCore(_vault, _head, _length, _storage) {
}
function setProxy(JouleProxyAPI _proxy) public onlyOwner {
proxy = _proxy;
}
modifier onlyProxy() {
require(msg.sender == address(proxy));
_;
}
function setMinGasPrice(uint _minGasPrice) public onlyOwner {
require(_minGasPrice >= MIN_GAS_PRICE);
require(_minGasPrice <= MAX_GAS_PRICE);
minGasPriceGwei = uint32(_minGasPrice / GWEI);
}
function registerFor(address _registrant, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public payable onlyProxy returns (uint) {
return innerRegister(_registrant, _address, _timestamp, _gasLimit, _gasPrice);
}
function unregisterFor(address _registrant, bytes32 _key, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public onlyProxy returns (uint) {
return innerUnregister(_registrant, _key, _address, _timestamp, _gasLimit, _gasPrice);
}
function invokeFor(address _invoker) public onlyProxy returns (uint) {
return innerInvoke(_invoker);
}
function invokeOnceFor(address _invoker) public onlyProxy returns (uint) {
return innerInvokeOnce(_invoker);
}
function invokeCallback(address _invoker, KeysUtils.Object memory _record) internal returns (bool) {
return proxy.callback(_invoker, _record.contractAddress, _record.timestamp, _record.gasLimit, _record.gasPriceGwei * GWEI);
}
}
contract JouleProxy is JouleProxyAPI, JouleAPI, Ownable, TransferToken, usingConsts {
JouleBehindProxy public joule;
function setJoule(JouleBehindProxy _joule) public onlyOwner {
joule = _joule;
}
modifier onlyJoule() {
require(msg.sender == address(joule));
_;
}
function () public payable {
}
function getCount() public view returns (uint) {
return joule.getCount();
}
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint) {
return registerFor(msg.sender, _address, _timestamp, _gasLimit, _gasPrice);
}
function registerFor(address _registrant, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public payable returns (uint) {
Registered(_registrant, _address, _timestamp, _gasLimit, _gasPrice);
uint change = joule.registerFor.value(msg.value)(_registrant, _address, _timestamp, _gasLimit, _gasPrice);
if (change > 0) {
msg.sender.transfer(change);
}
return change;
}
function unregister(bytes32 _key, address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external returns (uint) {
// unregister will return funds to registrant, not to msg.sender (unlike register)
uint amount = joule.unregisterFor(msg.sender, _key, _address, _timestamp, _gasLimit, _gasPrice);
Unregistered(msg.sender, _address, _timestamp, _gasLimit, _gasPrice, amount);
return amount;
}
function findKey(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) public view returns (bytes32) {
return joule.findKey(_address, _timestamp, _gasLimit, _gasPrice);
}
function invoke() public returns (uint) {
return invokeFor(msg.sender);
}
function invokeFor(address _invoker) public returns (uint) {
uint amount = joule.invokeFor(_invoker);
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function invokeOnce() public returns (uint) {
return invokeOnceFor(msg.sender);
}
function invokeOnceFor(address _invoker) public returns (uint) {
uint amount = joule.invokeOnceFor(_invoker);
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint) {
return joule.getPrice(_gasLimit, _gasPrice);
}
function getTopOnce() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice,
uint invokeGas,
uint rewardAmount
) {
(contractAddress, timestamp, gasLimit, gasPrice, invokeGas, rewardAmount) = joule.getTopOnce();
}
function getNextOnce(address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) public view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice,
uint invokeGas,
uint rewardAmount
) {
(contractAddress, timestamp, gasLimit, gasPrice, invokeGas, rewardAmount) = joule.getNextOnce(_contractAddress, _timestamp, _gasLimit, _gasPrice);
}
function getNext(uint _count,
address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) external view returns (
address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices,
uint[] _invokeGases,
uint[] _rewardAmounts
) {
_addresses = new address[](_count);
_timestamps = new uint[](_count);
_gasLimits = new uint[](_count);
_gasPrices = new uint[](_count);
_invokeGases = new uint[](_count);
_rewardAmounts = new uint[](_count);
uint i = 0;
(_addresses[i], _timestamps[i], _gasLimits[i], _gasPrices[i], _invokeGases[i], _rewardAmounts[i]) = joule.getNextOnce(_contractAddress, _timestamp, _gasLimit, _gasPrice);
for (i += 1; i < _count; i ++) {
if (_timestamps[i - 1] == 0) {
break;
}
(_addresses[i], _timestamps[i], _gasLimits[i], _gasPrices[i], _invokeGases[i], _rewardAmounts[i]) = joule.getNextOnce(_addresses[i - 1], _timestamps[i - 1], _gasLimits[i - 1], _gasPrices[i - 1]);
}
}
function getTop(uint _count) external view returns (
address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices,
uint[] _invokeGases,
uint[] _rewardAmounts
) {
uint length = joule.getCount();
uint amount = _count <= length ? _count : length;
_addresses = new address[](amount);
_timestamps = new uint[](amount);
_gasLimits = new uint[](amount);
_gasPrices = new uint[](amount);
_invokeGases = new uint[](amount);
_rewardAmounts = new uint[](amount);
uint i = 0;
(_addresses[i], _timestamps[i], _gasLimits[i], _gasPrices[i], _invokeGases[i], _rewardAmounts[i]) = joule.getTopOnce();
for (i += 1; i < amount; i ++) {
(_addresses[i], _timestamps[i], _gasLimits[i], _gasPrices[i], _invokeGases[i], _rewardAmounts[i]) = joule.getNextOnce(_addresses[i - 1], _timestamps[i - 1], _gasLimits[i - 1], _gasPrices[i - 1]);
}
}
function getVersion() external view returns (bytes8) {
return joule.getVersion();
}
function getMinGasPrice() public view returns (uint) {
return joule.minGasPriceGwei() * GWEI;
}
function callback(address _invoker, address _address, uint, uint _gasLimit, uint) public onlyJoule returns (bool) {
require(msg.gas >= _gasLimit);
uint gas = msg.gas;
bool status = _address.call.gas(_gasLimit)(0x919840ad);
Invoked(_invoker, _address, status, gas - msg.gas);
return status;
}
} | 0x0...00000000000000000 ^^^^^^^^ - rounder marker (eg, to avoid crossing first day of year with year) ^^^^^^^^ - rounded moment (year, week, etc) | function toKey(uint _timestamp, uint rounder) pure private returns (bytes32 result) {
assembly {
result := or(mul(rounder, 0x100000000), mul(div(_timestamp, rounder), rounder))
}
}
| 13,055,785 | [
1,
20,
92,
20,
2777,
12648,
2787,
11706,
3639,
3602,
20254,
12800,
66,
300,
721,
9341,
5373,
261,
1332,
16,
358,
4543,
6828,
310,
1122,
2548,
434,
3286,
598,
3286,
13,
7734,
3602,
20254,
12800,
66,
300,
16729,
10382,
261,
6874,
16,
4860,
16,
5527,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
358,
653,
12,
11890,
389,
5508,
16,
2254,
721,
9341,
13,
16618,
3238,
1135,
261,
3890,
1578,
563,
13,
288,
203,
3639,
19931,
288,
203,
5411,
563,
519,
578,
12,
16411,
12,
303,
9341,
16,
374,
92,
21,
12648,
3631,
14064,
12,
2892,
24899,
5508,
16,
721,
9341,
3631,
721,
9341,
3719,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title KYC
* @dev KYC contract handles the white list for ASTCrowdsale contract
* Only accounts registered in KYC contract can buy AST token.
* Admins can register account, and the reason why
*/
contract KYC is Ownable {
// check the address is registered for token sale
mapping (address => bool) public registeredAddress;
// check the address is admin of kyc contract
mapping (address => bool) public admin;
event Registered(address indexed _addr);
event Unregistered(address indexed _addr);
event NewAdmin(address indexed _addr);
event ClaimedTokens(address _token, address owner, uint256 balance);
/**
* @dev check whether the address is registered for token sale or not.
* @param _addr address
*/
modifier onlyRegistered(address _addr) {
require(registeredAddress[_addr]);
_;
}
/**
* @dev check whether the msg.sender is admin or not
*/
modifier onlyAdmin() {
require(admin[msg.sender]);
_;
}
function KYC() {
admin[msg.sender] = true;
}
/**
* @dev set new admin as admin of KYC contract
* @param _addr address The address to set as admin of KYC contract
*/
function setAdmin(address _addr)
public
onlyOwner
{
require(_addr != address(0) && admin[_addr] == false);
admin[_addr] = true;
NewAdmin(_addr);
}
/**
* @dev register the address for token sale
* @param _addr address The address to register for token sale
*/
function register(address _addr)
public
onlyAdmin
{
require(_addr != address(0) && registeredAddress[_addr] == false);
registeredAddress[_addr] = true;
Registered(_addr);
}
/**
* @dev register the addresses for token sale
* @param _addrs address[] The addresses to register for token sale
*/
function registerByList(address[] _addrs)
public
onlyAdmin
{
for(uint256 i = 0; i < _addrs.length; i++) {
require(_addrs[i] != address(0) && registeredAddress[_addrs[i]] == false);
registeredAddress[_addrs[i]] = true;
Registered(_addrs[i]);
}
}
/**
* @dev unregister the registered address
* @param _addr address The address to unregister for token sale
*/
function unregister(address _addr)
public
onlyAdmin
onlyRegistered(_addr)
{
registeredAddress[_addr] = false;
Unregistered(_addr);
}
/**
* @dev unregister the registered addresses
* @param _addrs address[] The addresses to unregister for token sale
*/
function unregisterByList(address[] _addrs)
public
onlyAdmin
{
for(uint256 i = 0; i < _addrs.length; i++) {
require(registeredAddress[_addrs[i]]);
registeredAddress[_addrs[i]] = false;
Unregistered(_addrs[i]);
}
}
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `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;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @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) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @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 doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// 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((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @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 constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
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
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;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
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 Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract ATC is MiniMeToken {
mapping (address => bool) public blacklisted;
bool public generateFinished;
// @dev ATC constructor just parametrizes the MiniMeToken constructor
function ATC(address _tokenFactory)
MiniMeToken(
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"ATCon Token", // Token name
18, // Decimals
"ATC", // Symbol
false // Enable transfers
) {}
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
require(generateFinished == false);
//check msg.sender (controller ??)
return super.generateTokens(_owner, _amount);
}
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
require(blacklisted[_from] == false);
return super.doTransfer(_from, _to, _amount);
}
function finishGenerating() public onlyController returns (bool success) {
generateFinished = true;
return true;
}
function blacklistAccount(address tokenOwner) public onlyController returns (bool success) {
blacklisted[tokenOwner] = true;
return true;
}
function unBlacklistAccount(address tokenOwner) public onlyController returns (bool success) {
blacklisted[tokenOwner] = false;
return true;
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable, SafeMath{
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
mapping (address => uint256) public refunded;
State public state;
address[] public reserveWallet;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* @dev This constructor sets the addresses of
* 10 reserve wallets.
* and forwarding it if crowdsale is successful.
* @param _reserveWallet address[5] The addresses of reserve wallet.
*/
function RefundVault(address[] _reserveWallet) {
state = State.Active;
reserveWallet = _reserveWallet;
}
/**
* @dev This function is called when user buy tokens. Only RefundVault
* contract stores the Ether user sent which forwarded from crowdsale
* contract.
* @param investor address The address who buy the token from crowdsale.
*/
function deposit(address investor) onlyOwner payable {
require(state == State.Active);
deposited[investor] = add(deposited[investor], msg.value);
}
event Transferred(address _to, uint _value);
/**
* @dev This function is called when crowdsale is successfully finalized.
*/
function close() onlyOwner {
require(state == State.Active);
state = State.Closed;
uint256 balance = this.balance;
uint256 reserveAmountForEach = div(balance, reserveWallet.length);
for(uint8 i = 0; i < reserveWallet.length; i++){
reserveWallet[i].transfer(reserveAmountForEach);
Transferred(reserveWallet[i], reserveAmountForEach);
}
Closed();
}
/**
* @dev This function is called when crowdsale is unsuccessfully finalized
* and refund is required.
*/
function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
/**
* @dev This function allows for user to refund Ether.
*/
function refund(address investor) returns (bool) {
require(state == State.Refunding);
if (refunded[investor] > 0) {
return false;
}
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
refunded[investor] = depositedValue;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
return true;
}
}
/**
* @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 allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused {
paused = false;
Unpause();
}
}
contract ATCCrowdSale is Ownable, SafeMath, Pausable {
KYC public kyc;
ATC public token;
RefundVault public vault;
address public presale;
address public bountyAddress; //5% for bounty
address public partnersAddress; //15% for community groups & partners
address public ATCReserveLocker; //15% with 2 years lock
address public teamLocker; // 15% with 2 years vesting
struct Period {
uint256 startTime;
uint256 endTime;
uint256 bonus; // used to calculate rate with bonus. ragne 0 ~ 15 (0% ~ 15%)
}
uint256 public baseRate; // 1 ETH = 1500 ATC
uint256[] public additionalBonusAmounts;
Period[] public periods;
uint8 constant public MAX_PERIOD_COUNT = 8;
uint256 public weiRaised;
uint256 public maxEtherCap;
uint256 public minEtherCap;
mapping (address => uint256) public beneficiaryFunded;
address[] investorList;
mapping (address => bool) inInvestorList;
address public ATCController;
bool public isFinalized;
uint256 public refundCompleted;
bool public presaleFallBackCalled;
uint256 public finalizedTime;
bool public initialized;
event CrowdSaleTokenPurchase(address indexed _investor, address indexed _beneficiary, uint256 _toFund, uint256 _tokens);
event StartPeriod(uint256 _startTime, uint256 _endTime, uint256 _bonus);
event Finalized();
event PresaleFallBack(uint256 _presaleWeiRaised);
event PushInvestorList(address _investor);
event RefundAll(uint256 _numToRefund);
event ClaimedTokens(address _claimToken, address owner, uint256 balance);
event Initialize();
function initialize (
address _kyc,
address _token,
address _vault,
address _presale,
address _bountyAddress,
address _partnersAddress,
address _ATCReserveLocker,
address _teamLocker,
address _tokenController,
uint256 _maxEtherCap,
uint256 _minEtherCap,
uint256 _baseRate,
uint256[] _additionalBonusAmounts
) onlyOwner {
require(!initialized);
require(_kyc != 0x00 && _token != 0x00 && _vault != 0x00 && _presale != 0x00);
require(_bountyAddress != 0x00 && _partnersAddress != 0x00);
require(_ATCReserveLocker != 0x00 && _teamLocker != 0x00);
require(_tokenController != 0x00);
require(0 < _minEtherCap && _minEtherCap < _maxEtherCap);
require(_baseRate > 0);
require(_additionalBonusAmounts[0] > 0);
for (uint i = 0; i < _additionalBonusAmounts.length - 1; i++) {
require(_additionalBonusAmounts[i] < _additionalBonusAmounts[i + 1]);
}
kyc = KYC(_kyc);
token = ATC(_token);
vault = RefundVault(_vault);
presale = _presale;
bountyAddress = _bountyAddress;
partnersAddress = _partnersAddress;
ATCReserveLocker = _ATCReserveLocker;
teamLocker = _teamLocker;
ATCController = _tokenController;
maxEtherCap = _maxEtherCap;
minEtherCap = _minEtherCap;
baseRate = _baseRate;
additionalBonusAmounts = _additionalBonusAmounts;
initialized = true;
Initialize();
}
function () public payable {
buy(msg.sender);
}
function presaleFallBack(uint256 _presaleWeiRaised) public returns (bool) {
require(!presaleFallBackCalled);
require(msg.sender == presale);
weiRaised = _presaleWeiRaised;
presaleFallBackCalled = true;
PresaleFallBack(_presaleWeiRaised);
return true;
}
function buy(address beneficiary)
public
payable
whenNotPaused
{
// check validity
require(presaleFallBackCalled);
require(beneficiary != 0x00);
require(kyc.registeredAddress(beneficiary));
require(onSale());
require(validPurchase());
require(!isFinalized);
// calculate eth amount
uint256 weiAmount = msg.value;
uint256 toFund;
uint256 postWeiRaised = add(weiRaised, weiAmount);
if (postWeiRaised > maxEtherCap) {
toFund = sub(maxEtherCap, weiRaised);
} else {
toFund = weiAmount;
}
require(toFund > 0);
require(weiAmount >= toFund);
uint256 rate = calculateRate(toFund);
uint256 tokens = mul(toFund, rate);
uint256 toReturn = sub(weiAmount, toFund);
pushInvestorList(msg.sender);
weiRaised = add(weiRaised, toFund);
beneficiaryFunded[beneficiary] = add(beneficiaryFunded[beneficiary], toFund);
token.generateTokens(beneficiary, tokens);
if (toReturn > 0) {
msg.sender.transfer(toReturn);
}
forwardFunds(toFund);
CrowdSaleTokenPurchase(msg.sender, beneficiary, toFund, tokens);
}
function pushInvestorList(address investor) internal {
if (!inInvestorList[investor]) {
inInvestorList[investor] = true;
investorList.push(investor);
PushInvestorList(investor);
}
}
function validPurchase() internal view returns (bool) {
bool nonZeroPurchase = msg.value != 0;
return nonZeroPurchase && !maxReached();
}
function forwardFunds(uint256 toFund) internal {
vault.deposit.value(toFund)(msg.sender);
}
/**
* @dev Checks whether minEtherCap is reached
* @return true if min ether cap is reaced
*/
function minReached() public view returns (bool) {
return weiRaised >= minEtherCap;
}
/**
* @dev Checks whether maxEtherCap is reached
* @return true if max ether cap is reaced
*/
function maxReached() public view returns (bool) {
return weiRaised == maxEtherCap;
}
function getPeriodBonus() public view returns (uint256) {
bool nowOnSale;
uint256 currentPeriod;
for (uint i = 0; i < periods.length; i++) {
if (periods[i].startTime <= now && now <= periods[i].endTime) {
nowOnSale = true;
currentPeriod = i;
break;
}
}
require(nowOnSale);
return periods[currentPeriod].bonus;
}
/**
* @dev rate = baseRate * (100 + bonus) / 100
*/
function calculateRate(uint256 toFund) public view returns (uint256) {
uint bonus = getPeriodBonus();
// bonus for eth amount
if (additionalBonusAmounts[0] <= toFund) {
bonus = add(bonus, 5); // 5% amount bonus for more than 300 ETH
}
if (additionalBonusAmounts[1] <= toFund) {
bonus = add(bonus, 5); // 10% amount bonus for more than 6000 ETH
}
if (additionalBonusAmounts[2] <= toFund) {
bonus = 25; // final 25% amount bonus for more than 8000 ETH
}
if (additionalBonusAmounts[3] <= toFund) {
bonus = 30; // final 30% amount bonus for more than 10000 ETH
}
return div(mul(baseRate, add(bonus, 100)), 100);
}
function startPeriod(uint256 _startTime, uint256 _endTime) public onlyOwner returns (bool) {
require(periods.length < MAX_PERIOD_COUNT);
require(now < _startTime && _startTime < _endTime);
if (periods.length != 0) {
require(sub(_endTime, _startTime) <= 7 days);
require(periods[periods.length - 1].endTime < _startTime);
}
// 15% -> 10% -> 5% -> 0%
Period memory newPeriod;
newPeriod.startTime = _startTime;
newPeriod.endTime = _endTime;
if(periods.length < 3) {
newPeriod.bonus = sub(15, mul(5, periods.length));
} else {
newPeriod.bonus = 0;
}
periods.push(newPeriod);
StartPeriod(_startTime, _endTime, newPeriod.bonus);
return true;
}
function onSale() public returns (bool) {
bool nowOnSale;
for (uint i = 0; i < periods.length; i++) {
if (periods[i].startTime <= now && now <= periods[i].endTime) {
nowOnSale = true;
break;
}
}
return nowOnSale;
}
/**
* @dev should be called after crowdsale ends, to do
*/
function finalize() onlyOwner {
require(!isFinalized);
require(!onSale() || maxReached());
finalizedTime = now;
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev end token minting on finalization, mint tokens for dev team and reserve wallets
*/
function finalization() internal {
if (minReached()) {
vault.close();
uint256 totalToken = token.totalSupply();
// token distribution : 50% for sale, 5% for bounty, 15% for partners, 15% for reserve, 15% for team
uint256 bountyAmount = div(mul(totalToken, 5), 50);
uint256 partnersAmount = div(mul(totalToken, 15), 50);
uint256 reserveAmount = div(mul(totalToken, 15), 50);
uint256 teamAmount = div(mul(totalToken, 15), 50);
distributeToken(bountyAmount, partnersAmount, reserveAmount, teamAmount);
token.enableTransfers(true);
} else {
vault.enableRefunds();
}
token.finishGenerating();
token.changeController(ATCController);
}
function distributeToken(uint256 bountyAmount, uint256 partnersAmount, uint256 reserveAmount, uint256 teamAmount) internal {
require(bountyAddress != 0x00 && partnersAddress != 0x00);
require(ATCReserveLocker != 0x00 && teamLocker != 0x00);
token.generateTokens(bountyAddress, bountyAmount);
token.generateTokens(partnersAddress, partnersAmount);
token.generateTokens(ATCReserveLocker, reserveAmount);
token.generateTokens(teamLocker, teamAmount);
}
/**
* @dev refund a lot of investors at a time checking onlyOwner
* @param numToRefund uint256 The number of investors to refund
*/
function refundAll(uint256 numToRefund) onlyOwner {
require(isFinalized);
require(!minReached());
require(numToRefund > 0);
uint256 limit = refundCompleted + numToRefund;
if (limit > investorList.length) {
limit = investorList.length;
}
for(uint256 i = refundCompleted; i < limit; i++) {
vault.refund(investorList[i]);
}
refundCompleted = limit;
RefundAll(numToRefund);
}
/**
* @dev if crowdsale is unsuccessful, investors can claim refunds here
* @param investor address The account to be refunded
*/
function claimRefund(address investor) returns (bool) {
require(isFinalized);
require(!minReached());
return vault.refund(investor);
}
function claimTokens(address _claimToken) public onlyOwner {
if (token.controller() == address(this)) {
token.claimTokens(_claimToken);
}
if (_claimToken == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Basic claimToken = ERC20Basic(_claimToken);
uint256 balance = claimToken.balanceOf(this);
claimToken.transfer(owner, balance);
ClaimedTokens(_claimToken, owner, balance);
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract ReserveLocker is SafeMath{
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
ATCCrowdSale public crowdsale;
address public beneficiary;
function ReserveLocker(address _token, address _crowdsale, address _beneficiary) {
require(_token != 0x00);
require(_crowdsale != 0x00);
require(_beneficiary != 0x00);
token = ERC20Basic(_token);
crowdsale = ATCCrowdSale(_crowdsale);
beneficiary = _beneficiary;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
uint256 finalizedTime = crowdsale.finalizedTime();
require(finalizedTime > 0 && now > add(finalizedTime, 2 years));
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
function setToken(address newToken) public {
require(msg.sender == beneficiary);
require(newToken != 0x00);
token = ERC20Basic(newToken);
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TeamLocker is SafeMath{
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
ATCCrowdSale public crowdsale;
address[] public beneficiaries;
uint256 public collectedTokens;
function TeamLocker(address _token, address _crowdsale, address[] _beneficiaries) {
require(_token != 0x00);
require(_crowdsale != 0x00);
for (uint i = 0; i < _beneficiaries.length; i++) {
require(_beneficiaries[i] != 0x00);
}
token = ERC20Basic(_token);
crowdsale = ATCCrowdSale(_crowdsale);
beneficiaries = _beneficiaries;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
uint256 balance = token.balanceOf(address(this));
uint256 total = add(balance, collectedTokens);
uint256 finalizedTime = crowdsale.finalizedTime();
require(finalizedTime > 0);
uint256 lockTime1 = add(finalizedTime, 183 days); // 6 months
uint256 lockTime2 = add(finalizedTime, 1 years); // 1 year
uint256 currentRatio = 20;
if (now >= lockTime1) {
currentRatio = 50;
}
if (now >= lockTime2) {
currentRatio = 100;
}
uint256 releasedAmount = div(mul(total, currentRatio), 100);
uint256 grantAmount = sub(releasedAmount, collectedTokens);
require(grantAmount > 0);
collectedTokens = add(collectedTokens, grantAmount);
uint256 grantAmountForEach = div(grantAmount, 3);
for (uint i = 0; i < beneficiaries.length; i++) {
token.safeTransfer(beneficiaries[i], grantAmountForEach);
}
}
function setToken(address newToken) public {
require(newToken != 0x00);
bool isBeneficiary;
for (uint i = 0; i < beneficiaries.length; i++) {
if (msg.sender == beneficiaries[i]) {
isBeneficiary = true;
}
}
require(isBeneficiary);
token = ERC20Basic(newToken);
}
} | * @title TokenTimelock @dev TokenTimelock is a token holder contract that will allow a beneficiary to extract the tokens after a given release time/ | contract ReserveLocker is SafeMath{
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
ATCCrowdSale public crowdsale;
address public beneficiary;
function ReserveLocker(address _token, address _crowdsale, address _beneficiary) {
require(_token != 0x00);
require(_crowdsale != 0x00);
require(_beneficiary != 0x00);
token = ERC20Basic(_token);
crowdsale = ATCCrowdSale(_crowdsale);
beneficiary = _beneficiary;
}
function release() public {
uint256 finalizedTime = crowdsale.finalizedTime();
require(finalizedTime > 0 && now > add(finalizedTime, 2 years));
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
function setToken(address newToken) public {
require(msg.sender == beneficiary);
require(newToken != 0x00);
token = ERC20Basic(newToken);
}
}
| 2,528,850 | [
1,
1345,
10178,
292,
975,
225,
3155,
10178,
292,
975,
353,
279,
1147,
10438,
6835,
716,
903,
1699,
279,
27641,
74,
14463,
814,
358,
2608,
326,
2430,
1839,
279,
864,
3992,
813,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1124,
6527,
2531,
264,
353,
14060,
10477,
95,
203,
225,
1450,
14060,
654,
39,
3462,
364,
4232,
39,
3462,
8252,
31,
203,
225,
4232,
39,
3462,
8252,
1071,
1147,
31,
203,
225,
14464,
6743,
492,
72,
30746,
1071,
276,
492,
2377,
5349,
31,
203,
225,
1758,
1071,
27641,
74,
14463,
814,
31,
203,
225,
445,
1124,
6527,
2531,
264,
12,
2867,
389,
2316,
16,
1758,
389,
71,
492,
2377,
5349,
16,
1758,
389,
70,
4009,
74,
14463,
814,
13,
288,
203,
565,
2583,
24899,
2316,
480,
374,
92,
713,
1769,
203,
565,
2583,
24899,
71,
492,
2377,
5349,
480,
374,
92,
713,
1769,
203,
565,
2583,
24899,
70,
4009,
74,
14463,
814,
480,
374,
92,
713,
1769,
203,
565,
1147,
273,
4232,
39,
3462,
8252,
24899,
2316,
1769,
203,
565,
276,
492,
2377,
5349,
273,
14464,
6743,
492,
72,
30746,
24899,
71,
492,
2377,
5349,
1769,
203,
565,
27641,
74,
14463,
814,
273,
389,
70,
4009,
74,
14463,
814,
31,
203,
225,
289,
203,
282,
445,
3992,
1435,
1071,
288,
203,
377,
2254,
5034,
727,
1235,
950,
273,
276,
492,
2377,
5349,
18,
6385,
1235,
950,
5621,
203,
377,
2583,
12,
6385,
1235,
950,
405,
374,
597,
2037,
405,
527,
12,
6385,
1235,
950,
16,
576,
11387,
10019,
203,
377,
2254,
5034,
3844,
273,
1147,
18,
12296,
951,
12,
2211,
1769,
203,
377,
2583,
12,
8949,
405,
374,
1769,
203,
377,
1147,
18,
4626,
5912,
12,
70,
4009,
74,
14463,
814,
16,
3844,
1769,
203,
282,
289,
203,
225,
445,
22629,
12,
2867,
2
]
|
./partial_match/4/0xc1b59cc9253ee4Bf30e12c6d06A101401c5470d8/sources/ExchangeV1.sol | Sig calldata buyerFeeSig,validateBuyerFeeSig(order, buyerFee, buyerFeeSig); | function exchange(
Order calldata order,
Sig calldata sig,
uint buyerFee,
uint amount,
address buyer
) payable external {
validateOrderSig(order, sig);
uint paying = order.buying.mul(amount).div(order.selling);
verifyOpenAndModifyOrderState(order.key, order.selling, amount);
require(order.key.sellAsset.assetType != AssetType.ETH, "ETH is not supported on sell side");
if (order.key.buyAsset.assetType == AssetType.ETH) {
validateEthTransfer(paying, buyerFee);
}
FeeSide feeSide = getFeeSide(order.key.sellAsset.assetType, order.key.buyAsset.assetType);
if (buyer == address(0x0)) {
buyer = msg.sender;
}
transferWithFeesPossibility(order.key.sellAsset, amount, order.key.owner, buyer, feeSide == FeeSide.SELL, buyerFee, order.sellerFee, order.key.buyAsset);
transferWithFeesPossibility(order.key.buyAsset, paying, msg.sender, order.key.owner, feeSide == FeeSide.BUY, order.sellerFee, buyerFee, order.key.sellAsset);
emitBuy(order, amount, buyer);
}
| 8,560,886 | [
1,
8267,
745,
892,
27037,
14667,
8267,
16,
5662,
38,
16213,
14667,
8267,
12,
1019,
16,
27037,
14667,
16,
27037,
14667,
8267,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7829,
12,
203,
3639,
4347,
745,
892,
1353,
16,
203,
3639,
21911,
745,
892,
3553,
16,
203,
3639,
2254,
27037,
14667,
16,
203,
3639,
2254,
3844,
16,
203,
3639,
1758,
27037,
203,
565,
262,
8843,
429,
3903,
288,
203,
3639,
1954,
2448,
8267,
12,
1019,
16,
3553,
1769,
203,
3639,
2254,
8843,
310,
273,
1353,
18,
70,
9835,
310,
18,
16411,
12,
8949,
2934,
2892,
12,
1019,
18,
87,
1165,
310,
1769,
203,
3639,
3929,
3678,
1876,
11047,
2448,
1119,
12,
1019,
18,
856,
16,
1353,
18,
87,
1165,
310,
16,
3844,
1769,
203,
3639,
2583,
12,
1019,
18,
856,
18,
87,
1165,
6672,
18,
9406,
559,
480,
10494,
559,
18,
1584,
44,
16,
315,
1584,
44,
353,
486,
3260,
603,
357,
80,
4889,
8863,
203,
3639,
309,
261,
1019,
18,
856,
18,
70,
9835,
6672,
18,
9406,
559,
422,
10494,
559,
18,
1584,
44,
13,
288,
203,
5411,
1954,
41,
451,
5912,
12,
10239,
310,
16,
27037,
14667,
1769,
203,
3639,
289,
203,
3639,
30174,
8895,
14036,
8895,
273,
2812,
1340,
8895,
12,
1019,
18,
856,
18,
87,
1165,
6672,
18,
9406,
559,
16,
1353,
18,
856,
18,
70,
9835,
6672,
18,
9406,
559,
1769,
203,
3639,
309,
261,
70,
16213,
422,
1758,
12,
20,
92,
20,
3719,
288,
203,
5411,
27037,
273,
1234,
18,
15330,
31,
203,
3639,
289,
203,
3639,
7412,
1190,
2954,
281,
1616,
17349,
12,
1019,
18,
856,
18,
87,
1165,
6672,
16,
3844,
16,
1353,
18,
856,
18,
8443,
16,
27037,
16,
14036,
8895,
422,
30174,
2
]
|
pragma solidity ^0.4.23;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* @dev and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
"\x19Ethereum Signed Message:\n32",
hash
);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract Arbitrator is Ownable {
mapping(address => bool) private aribitratorWhitelist;
address private primaryArbitrator;
event ArbitratorAdded(address indexed newArbitrator);
event ArbitratorRemoved(address indexed newArbitrator);
event ChangePrimaryArbitratorWallet(address indexed newPrimaryWallet);
constructor() public {
primaryArbitrator = msg.sender;
}
modifier onlyArbitrator() {
require(aribitratorWhitelist[msg.sender] == true || msg.sender == primaryArbitrator);
_;
}
function changePrimaryArbitrator(address walletAddress) public onlyOwner {
require(walletAddress != address(0));
emit ChangePrimaryArbitratorWallet(walletAddress);
primaryArbitrator = walletAddress;
}
function addArbitrator(address newArbitrator) public onlyOwner {
require(newArbitrator != address(0));
emit ArbitratorAdded(newArbitrator);
aribitratorWhitelist[newArbitrator] = true;
}
function deleteArbitrator(address arbitrator) public onlyOwner {
require(arbitrator != address(0));
require(arbitrator != msg.sender); //ensure owner isn't removed
emit ArbitratorRemoved(arbitrator);
delete aribitratorWhitelist[arbitrator];
}
//Mainly for front-end administration
function isArbitrator(address arbitratorCheck) external view returns(bool) {
return (aribitratorWhitelist[arbitratorCheck] || arbitratorCheck == primaryArbitrator);
}
}
contract ApprovedWithdrawer is Ownable {
mapping(address => bool) private withdrawerWhitelist;
address private primaryWallet;
event WalletApproved(address indexed newAddress);
event WalletRemoved(address indexed removedAddress);
event ChangePrimaryApprovedWallet(address indexed newPrimaryWallet);
constructor() public {
primaryWallet = msg.sender;
}
modifier onlyApprovedWallet(address _to) {
require(withdrawerWhitelist[_to] == true || primaryWallet == _to);
_;
}
function changePrimaryApprovedWallet(address walletAddress) public onlyOwner {
require(walletAddress != address(0));
emit ChangePrimaryApprovedWallet(walletAddress);
primaryWallet = walletAddress;
}
function addApprovedWalletAddress(address walletAddress) public onlyOwner {
require(walletAddress != address(0));
emit WalletApproved(walletAddress);
withdrawerWhitelist[walletAddress] = true;
}
function deleteApprovedWalletAddress(address walletAddress) public onlyOwner {
require(walletAddress != address(0));
require(walletAddress != msg.sender); //ensure owner isn't removed
emit WalletRemoved(walletAddress);
delete withdrawerWhitelist[walletAddress];
}
//Mainly for front-end administration
function isApprovedWallet(address walletCheck) external view returns(bool) {
return (withdrawerWhitelist[walletCheck] || walletCheck == primaryWallet);
}
}
/**
* @title CoinSparrow
*/
contract CoinSparrow is Ownable, Arbitrator, ApprovedWithdrawer, Pausable {
//Who wouldn't?
using SafeMath for uint256;
/**
* ------------------------------------
* SET UP SOME CONSTANTS FOR JOB STATUS
* ------------------------------------
*/
//Some of these are not used in the contract, but are for reference and are used in the front-end's database.
uint8 constant private STATUS_JOB_NOT_EXIST = 1; //Not used in contract. Here for reference (used externally)
uint8 constant private STATUS_JOB_CREATED = 2; //Job has been created. Set by createJobEscrow()
uint8 constant private STATUS_JOB_STARTED = 3; //Contractor flags job as started. Set by jobStarted()
uint8 constant private STATUS_HIRER_REQUEST_CANCEL = 4; //Hirer requested cancellation on started job.
//Set by requestMutualJobCancelation()
uint8 constant private STATUS_JOB_COMPLETED = 5; //Contractor flags job as completed. Set by jobCompleted()
uint8 constant private STATUS_JOB_IN_DISPUTE = 6; //Either party raised dispute. Set by requestDispute()
uint8 constant private STATUS_HIRER_CANCELLED = 7; //Not used in contract. Here for reference
uint8 constant private STATUS_CONTRACTOR_CANCELLED = 8; //Not used in contract. Here for reference
uint8 constant private STATUS_FINISHED_FUNDS_RELEASED = 9; //Not used in contract. Here for reference
uint8 constant private STATUS_FINISHED_FUNDS_RELEASED_BY_CONTRACTOR = 10; //Not used in contract. Here for reference
uint8 constant private STATUS_CONTRACTOR_REQUEST_CANCEL = 11; //Contractor requested cancellation on started job.
//Set by requestMutualJobCancelation()
uint8 constant private STATUS_MUTUAL_CANCELLATION_PROCESSED = 12; //Not used in contract. Here for reference
//Deployment script will check for existing CoinSparrow contracts, and only
//deploy if this value is > than existing version.
//TODO: to be implemented
uint8 constant private COINSPARROW_CONTRACT_VERSION = 1;
/**
* ------
* EVENTS
* ------
*/
event JobCreated(bytes32 _jobHash, address _who, uint256 _value);
event ContractorStartedJob(bytes32 _jobHash, address _who);
event ContractorCompletedJob(bytes32 _jobHash, address _who);
event HirerRequestedCancel(bytes32 _jobHash, address _who);
event ContractorRequestedCancel(bytes32 _jobHash, address _who);
event CancelledByHirer(bytes32 _jobHash, address _who);
event CancelledByContractor(bytes32 _jobHash, address _who);
event MutuallyAgreedCancellation(
bytes32 _jobHash,
address _who,
uint256 _hirerAmount,
uint256 _contractorAmount
);
event DisputeRequested(bytes32 _jobHash, address _who);
event DisputeResolved(
bytes32 _jobHash,
address _who,
uint256 _hirerAmount,
uint256 _contractorAmount
);
event HirerReleased(bytes32 _jobHash, address _hirer, address _contractor, uint256 _value);
event AddFeesToCoinSparrowPool(bytes32 _jobHash, uint256 _value);
event ContractorReleased(bytes32 _jobHash, address _hirer, address _contractor, uint256 _value);
event HirerLastResortRefund(bytes32 _jobHash, address _hirer, address _contractor, uint256 _value);
event WithdrawFeesFromCoinSparrowPool(address _whoCalled, address _to, uint256 _amount);
event LogFallbackFunctionCalled(address _from, uint256 _amount);
/**
* ----------
* STRUCTURES
* ----------
*/
/**
* @dev Structure to hold live Escrow data - current status, times etc.
*/
struct JobEscrow {
// Set so we know the job has already been created. Set when job created in createJobEscrow()
bool exists;
// The timestamp after which the hirer can cancel the task if the contractor has not yet flagged as job started.
// Set in createJobEscrow(). If the Contractor has not called jobStarted() within this time, then the hirer
// can call hirerCancel() to get a full refund (minus gas fees)
uint32 hirerCanCancelAfter;
//Job's current status (see STATUS_JOB_* constants above). Updated in multiple functions
uint8 status;
//timestamp for job completion. Set when jobCompleted() is called.
uint32 jobCompleteDate;
//num agreed seconds it will take to complete the job, once flagged as STATUS_JOB_STARTED. Set in createJobEscrow()
uint32 secondsToComplete;
//timestamp calculated for agreed completion date. Set when jobStarted() is called.
uint32 agreedCompletionDate;
}
/**
* ------------------
* CONTRACT VARIABLES
* ------------------
*/
//Total Wei currently held in Escrow
uint256 private totalInEscrow;
//Amount of Wei available to CoinSparrow to withdraw
uint256 private feesAvailableForWithdraw;
/*
* Set max limit for how much (in wei) contract will accept. Can be modified by owner using setMaxSend()
* This ensures that arbitrarily large amounts of ETH can't be sent.
* Front end will check this value before processing new jobs
*/
uint256 private MAX_SEND;
/*
* Mapping of active jobs. Key is a hash of the job data:
* JobEscrow = keccak256(_jobId,_hirer,_contractor, _value, _fee)
* Once job is complete, and refunds released, the
* mapping for that job is deleted to conserve space.
*/
mapping(bytes32 => JobEscrow) private jobEscrows;
/*
* mapping of Hirer's funds in Escrow for each job.
* This is referenced when any ETH transactions occur
*/
mapping(address => mapping(bytes32 => uint256)) private hirerEscrowMap;
/**
* ---------
* MODIFIERS
* ---------
*/
/**
* @dev modifier to ensure only the Hirer can execute
* @param _hirer Address of the hirer to check against msg.sender
*/
modifier onlyHirer(address _hirer) {
require(msg.sender == _hirer);
_;
}
/**
* @dev modifier to ensure only the Contractor can execute
* @param _contractor Address of the contractor to check against msg.sender
*/
modifier onlyContractor(address _contractor) {
require(msg.sender == _contractor);
_;
}
/**
* @dev modifier to ensure only the Contractor can execute
* @param _contractor Address of the contractor to check against msg.sender
*/
modifier onlyHirerOrContractor(address _hirer, address _contractor) {
require(msg.sender == _hirer || msg.sender == _contractor);
_;
}
/**
* ----------------------
* CONTRACT FUNCTIONALITY
* ----------------------
*/
/**
* @dev Constructor function for the contract
* @param _maxSend Maximum Wei the contract will accept in a transaction
*/
constructor(uint256 _maxSend) public {
require(_maxSend > 0);
//a bit of protection. Set a limit, so users can't send stupid amounts of ETH
MAX_SEND = _maxSend;
}
/**
* @dev fallback function for the contract. Log event so ETH can be tracked and returned
*/
function() payable {
//Log who sent, and how much so it can be returned
emit LogFallbackFunctionCalled(msg.sender, msg.value);
}
/**
* @dev Create a new escrow and add it to the `jobEscrows` mapping.
* Also updates/creates a reference to the job, and amount in Escrow for the job in hirerEscrowMap
* jobHash is created by hashing _jobId, _seller, _buyer, _value and _fee params.
* These params must be supplied on future contract calls.
* A hash of the job parameters (_jobId, _hirer, _contractor, _value, _fee) is created and used
* to access job data held in the contract. All functions that interact with a job in Escrow
* require these parameters.
* Pausable - only runs whenNotPaused. Can pause to prevent taking any more
* ETH if there is a problem with the Smart Contract.
* Parties can still access/transfer their existing ETH held in Escrow, complete jobs etc.
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @param _jobStartedWindowInSeconds time within which the contractor must flag as job started
* if job hasn't started AFTER this time, hirer can cancel contract.
* Hirer cannot cancel contract before this time.
* @param _secondsToComplete agreed time to complete job once it's flagged as STATUS_JOB_STARTED
*/
function createJobEscrow(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee,
uint32 _jobStartedWindowInSeconds,
uint32 _secondsToComplete
) payable external whenNotPaused onlyHirer(_hirer)
{
// Check sent eth against _value and also make sure is not 0
require(msg.value == _value && msg.value > 0);
//CoinSparrow's Fee should be less than the Job Value, because anything else would be daft.
require(_fee < _value);
//Check the amount sent is below the acceptable threshold
require(msg.value <= MAX_SEND);
//needs to be more than 0 seconds
require(_jobStartedWindowInSeconds > 0);
//needs to be more than 0 seconds
require(_secondsToComplete > 0);
//generate the job hash. Used to reference the job in all future function calls/transactions.
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//Check that the job does not already exist.
require(!jobEscrows[jobHash].exists);
//create the job and store it in the mapping
jobEscrows[jobHash] = JobEscrow(
true,
uint32(block.timestamp) + _jobStartedWindowInSeconds,
STATUS_JOB_CREATED,
0,
_secondsToComplete,
0);
//update total held in escrow
totalInEscrow = totalInEscrow.add(msg.value);
//Update hirer's job => value mapping
hirerEscrowMap[msg.sender][jobHash] = msg.value;
//Let the world know.
emit JobCreated(jobHash, msg.sender, msg.value);
}
/**
* -----------------------
* RELEASE FUNDS FUNCTIONS
* -----------------------
*/
/**
* @dev Release funds to contractor. Can only be called by Hirer. Can be called at any time as long as the
* job exists in the contract (for example, two parties may have agreed job is complete external to the
* CoinSparrow website). Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function hirerReleaseFunds(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyHirer(_hirer)
{
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
//check hirer has funds in the Smart Contract assigned to this job
require(hirerEscrowMap[msg.sender][jobHash] > 0);
//get the value from the stored hirer => job => value mapping
uint256 jobValue = hirerEscrowMap[msg.sender][jobHash];
//Check values in contract and sent are valid
require(jobValue > 0 && jobValue == _value);
//check fee amount is valid
require(jobValue >= jobValue.sub(_fee));
//check there is enough in escrow
require(totalInEscrow >= jobValue && totalInEscrow > 0);
//Log event
emit HirerReleased(
jobHash,
msg.sender,
_contractor,
jobValue);
//Log event
emit AddFeesToCoinSparrowPool(jobHash, _fee);
//no longer required. Remove to save storage. Also prevents reentrancy
delete jobEscrows[jobHash];
//no longer required. Remove to save storage. Also prevents reentrancy
delete hirerEscrowMap[msg.sender][jobHash];
//add to CoinSparrow's fee pool
feesAvailableForWithdraw = feesAvailableForWithdraw.add(_fee);
//update total in escrow
totalInEscrow = totalInEscrow.sub(jobValue);
//Finally, transfer the funds, minus CoinSparrow fees
_contractor.transfer(jobValue.sub(_fee));
}
/**
* @dev Release funds to contractor in the event that the Hirer is unresponsive after job has been flagged as complete.
* Can only be called by the contractor, and only 4 weeks after the job has been flagged as complete.
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function contractorReleaseFunds(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyContractor(_contractor)
{
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
//check job is actually completed
require(jobEscrows[jobHash].status == STATUS_JOB_COMPLETED);
//can only self-release 4 weeks after completion
require(block.timestamp > jobEscrows[jobHash].jobCompleteDate + 4 weeks);
//get value for job
uint256 jobValue = hirerEscrowMap[_hirer][jobHash];
//Check values in contract and sent are valid
require(jobValue > 0 && jobValue == _value);
//check fee amount is valid
require(jobValue >= jobValue.sub(_fee));
//check there is enough in escrow
require(totalInEscrow >= jobValue && totalInEscrow > 0);
emit ContractorReleased(
jobHash,
_hirer,
_contractor,
jobValue); //Log event
emit AddFeesToCoinSparrowPool(jobHash, _fee);
delete jobEscrows[jobHash]; //no longer required. Remove to save storage.
delete hirerEscrowMap[_hirer][jobHash]; //no longer required. Remove to save storage.
//add fees to coinsparrow pool
feesAvailableForWithdraw = feesAvailableForWithdraw.add(_fee);
//update total in escrow
totalInEscrow = totalInEscrow.sub(jobValue);
//transfer funds to contractor, minus fees
_contractor.transfer(jobValue.sub(_fee));
}
/**
* @dev Can be called by the hirer to claim a full refund, if job has been started but contractor has not
* completed within 4 weeks after agreed completion date, and becomes unresponsive.
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function hirerLastResortRefund(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyHirer(_hirer)
{
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
//check job is started
require(jobEscrows[jobHash].status == STATUS_JOB_STARTED);
//can only self-refund 4 weeks after agreed completion date
require(block.timestamp > jobEscrows[jobHash].agreedCompletionDate + 4 weeks);
//get value for job
uint256 jobValue = hirerEscrowMap[msg.sender][jobHash];
//Check values in contract and sent are valid
require(jobValue > 0 && jobValue == _value);
//check fee amount is valid
require(jobValue >= jobValue.sub(_fee));
//check there is enough in escrow
require(totalInEscrow >= jobValue && totalInEscrow > 0);
emit HirerLastResortRefund(
jobHash,
_hirer,
_contractor,
jobValue); //Log event
delete jobEscrows[jobHash]; //no longer required. Remove to save storage.
delete hirerEscrowMap[_hirer][jobHash]; //no longer required. Remove to save storage.
//update total in escrow
totalInEscrow = totalInEscrow.sub(jobValue);
//transfer funds to hirer
_hirer.transfer(jobValue);
}
/**
* ---------------------------
* UPDATE JOB STATUS FUNCTIONS
* ---------------------------
*/
/**
* @dev Flags job started, and Stops the hirer from cancelling the job.
* Can only be called the contractor when job starts.
* Used to mark the job as started. After this point, hirer must request cancellation
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function jobStarted(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyContractor(_contractor)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
//check job status.
require(jobEscrows[jobHash].status == STATUS_JOB_CREATED);
jobEscrows[jobHash].status = STATUS_JOB_STARTED; //set status
jobEscrows[jobHash].hirerCanCancelAfter = 0;
jobEscrows[jobHash].agreedCompletionDate = uint32(block.timestamp) + jobEscrows[jobHash].secondsToComplete;
emit ContractorStartedJob(jobHash, msg.sender);
}
/**
* @dev Flags job completed to inform hirer. Also sets flag to allow contractor to get their funds 4 weeks after
* completion in the event that the hirer is unresponsive and doesn't release the funds.
* Can only be called the contractor when job complete.
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function jobCompleted(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyContractor(_contractor)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
require(jobEscrows[jobHash].exists); //check the job exists in the contract
require(jobEscrows[jobHash].status == STATUS_JOB_STARTED); //check job status.
jobEscrows[jobHash].status = STATUS_JOB_COMPLETED;
jobEscrows[jobHash].jobCompleteDate = uint32(block.timestamp);
emit ContractorCompletedJob(jobHash, msg.sender);
}
/**
* --------------------------
* JOB CANCELLATION FUNCTIONS
* --------------------------
*/
/**
* @dev Cancels the job and returns the ether to the hirer.
* Can only be called the contractor. Can be called at any time during the process
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function contractorCancel(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyContractor(_contractor)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
uint256 jobValue = hirerEscrowMap[_hirer][jobHash];
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
//Check values in contract and sent are valid
require(jobValue > 0 && jobValue == _value);
//check fee amount is valid
require(jobValue >= jobValue.sub(_fee));
//check there is enough in escrow
require(totalInEscrow >= jobValue && totalInEscrow > 0);
delete jobEscrows[jobHash];
delete hirerEscrowMap[_hirer][jobHash];
emit CancelledByContractor(jobHash, msg.sender);
totalInEscrow = totalInEscrow.sub(jobValue);
_hirer.transfer(jobValue);
}
/**
* @dev Cancels the job and returns the ether to the hirer.
* Can only be called the hirer.
* Can only be called if the job start window was missed by the contractor
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function hirerCancel(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyHirer(_hirer)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
require(jobEscrows[jobHash].hirerCanCancelAfter > 0);
require(jobEscrows[jobHash].status == STATUS_JOB_CREATED);
require(jobEscrows[jobHash].hirerCanCancelAfter < block.timestamp);
uint256 jobValue = hirerEscrowMap[_hirer][jobHash];
//Check values in contract and sent are valid
require(jobValue > 0 && jobValue == _value);
//check fee amount is valid
require(jobValue >= jobValue.sub(_fee));
//check there is enough in escrow
require(totalInEscrow >= jobValue && totalInEscrow > 0);
delete jobEscrows[jobHash];
delete hirerEscrowMap[msg.sender][jobHash];
emit CancelledByHirer(jobHash, msg.sender);
totalInEscrow = totalInEscrow.sub(jobValue);
_hirer.transfer(jobValue);
}
/**
* @dev Called by the hirer or contractor to request mutual cancellation once job has started
* Can only be called when status = STATUS_JOB_STARTED
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function requestMutualJobCancellation(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyHirerOrContractor(_hirer, _contractor)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
require(jobEscrows[jobHash].status == STATUS_JOB_STARTED);
if (msg.sender == _hirer) {
jobEscrows[jobHash].status = STATUS_HIRER_REQUEST_CANCEL;
emit HirerRequestedCancel(jobHash, msg.sender);
}
if (msg.sender == _contractor) {
jobEscrows[jobHash].status = STATUS_CONTRACTOR_REQUEST_CANCEL;
emit ContractorRequestedCancel(jobHash, msg.sender);
}
}
/**
* @dev Called when both hirer and contractor have agreed on cancellation conditions, and amount each will receive
* can be called by hirer or contractor once % amount has been signed by both parties.
* Both parties sign a hash of the % agreed upon. The signatures of both parties must be sent and verified
* before the transaction is processed, to ensure that the % processed is valid.
* can be called at any time
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @param _contractorPercent percentage the contractor will be paid
* @param _hirerMsgSig Signed message from hiring party agreeing on _contractorPercent
* @param _contractorMsgSig Signed message from contractor agreeing on _contractorPercent
*/
function processMutuallyAgreedJobCancellation(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee,
uint8 _contractorPercent,
bytes _hirerMsgSig,
bytes _contractorMsgSig
) external
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
require(msg.sender == _hirer || msg.sender == _contractor);
require(_contractorPercent <= 100 && _contractorPercent >= 0);
//Checks the signature of both parties to ensure % is correct.
//Attempts to prevent the party calling the function from modifying the pre-agreed %
require(
checkRefundSignature(_contractorPercent,_hirerMsgSig,_hirer)&&
checkRefundSignature(_contractorPercent,_contractorMsgSig,_contractor));
uint256 jobValue = hirerEscrowMap[_hirer][jobHash];
//Check values in contract and sent are valid
require(jobValue > 0 && jobValue == _value);
//check fee amount is valid
require(jobValue >= jobValue.sub(_fee));
//check there is enough in escrow
require(totalInEscrow >= jobValue && totalInEscrow > 0);
totalInEscrow = totalInEscrow.sub(jobValue);
feesAvailableForWithdraw = feesAvailableForWithdraw.add(_fee);
delete jobEscrows[jobHash];
delete hirerEscrowMap[_hirer][jobHash];
uint256 contractorAmount = jobValue.sub(_fee).mul(_contractorPercent).div(100);
uint256 hirerAmount = jobValue.sub(_fee).mul(100 - _contractorPercent).div(100);
emit MutuallyAgreedCancellation(
jobHash,
msg.sender,
hirerAmount,
contractorAmount);
emit AddFeesToCoinSparrowPool(jobHash, _fee);
if (contractorAmount > 0) {
_contractor.transfer(contractorAmount);
}
if (hirerAmount > 0) {
_hirer.transfer(hirerAmount);
}
}
/**
* -------------------------
* DISPUTE RELATED FUNCTIONS
* -------------------------
*/
/**
* @dev Called by hirer or contractor to raise a dispute during started, completed or canellation request statuses
* Once called, funds are locked until arbitrator can resolve the dispute. Assigned arbitrator
* will review all information relating to the job, and decide on a fair course of action.
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
*/
function requestDispute(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) external onlyHirerOrContractor(_hirer, _contractor)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
require(
jobEscrows[jobHash].status == STATUS_JOB_STARTED||
jobEscrows[jobHash].status == STATUS_JOB_COMPLETED||
jobEscrows[jobHash].status == STATUS_HIRER_REQUEST_CANCEL||
jobEscrows[jobHash].status == STATUS_CONTRACTOR_REQUEST_CANCEL);
jobEscrows[jobHash].status = STATUS_JOB_IN_DISPUTE;
emit DisputeRequested(jobHash, msg.sender);
}
/**
* @dev Called by the arbitrator to resolve a dispute
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @param _contractorPercent percentage the contractor will receive
*/
function resolveDispute(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee,
uint8 _contractorPercent
) external onlyArbitrator
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
//check the job exists in the contract
require(jobEscrows[jobHash].exists);
require(jobEscrows[jobHash].status == STATUS_JOB_IN_DISPUTE);
require(_contractorPercent <= 100);
uint256 jobValue = hirerEscrowMap[_hirer][jobHash];
//Check values in contract and sent are valid
require(jobValue > 0 && jobValue == _value);
//check fee amount is valid
require(jobValue >= jobValue.sub(_fee));
//check there is enough in escrow
require(totalInEscrow >= jobValue && totalInEscrow > 0);
totalInEscrow = totalInEscrow.sub(jobValue);
feesAvailableForWithdraw = feesAvailableForWithdraw.add(_fee);
// Add the the pot for localethereum to withdraw
delete jobEscrows[jobHash];
delete hirerEscrowMap[_hirer][jobHash];
uint256 contractorAmount = jobValue.sub(_fee).mul(_contractorPercent).div(100);
uint256 hirerAmount = jobValue.sub(_fee).mul(100 - _contractorPercent).div(100);
emit DisputeResolved(
jobHash,
msg.sender,
hirerAmount,
contractorAmount);
emit AddFeesToCoinSparrowPool(jobHash, _fee);
_contractor.transfer(contractorAmount);
_hirer.transfer(hirerAmount);
}
/**
* ------------------------
* ADMINISTRATIVE FUNCTIONS
* ------------------------
*/
/**
* @dev Allows owner to transfer funds from the collected fees pool to an approved wallet address
* @param _to receiver wallet address
* @param _amount amount to withdraw and transfer
*/
function withdrawFees(address _to, uint256 _amount) onlyOwner onlyApprovedWallet(_to) external {
/**
* Withdraw fees collected by the contract. Only the owner can call this.
* Can only be sent to an approved wallet address
*/
require(_amount > 0);
require(_amount <= feesAvailableForWithdraw && feesAvailableForWithdraw > 0);
feesAvailableForWithdraw = feesAvailableForWithdraw.sub(_amount);
emit WithdrawFeesFromCoinSparrowPool(msg.sender,_to, _amount);
_to.transfer(_amount);
}
/**
* @dev returns how much has been collected in fees, and how much is available to withdraw
* @return feesAvailableForWithdraw amount available for CoinSparrow to withdraw
*/
function howManyFees() external view returns (uint256) {
return feesAvailableForWithdraw;
}
/**
* @dev returns how much is currently held in escrow
* @return totalInEscrow amount currently held in escrow
*/
function howMuchInEscrow() external view returns (uint256) {
return totalInEscrow;
}
/**
* @dev modify the maximum amount of ETH the contract will allow in a transaction (when creating a new job)
* @param _maxSend amount in Wei
*/
function setMaxSend(uint256 _maxSend) onlyOwner external {
require(_maxSend > 0);
MAX_SEND = _maxSend;
}
/**
* @dev return the current maximum amount the contract will allow in a transaction
* @return MAX_SEND current maximum value
*/
function getMaxSend() external view returns (uint256) {
return MAX_SEND;
}
/**
* @dev returns THIS contract instance's version
* @return COINSPARROW_CONTRACT_VERSION version number of THIS instance of the contract
*/
function getContractVersion() external pure returns(uint8) {
return COINSPARROW_CONTRACT_VERSION;
}
/**
* -------------------------
* JOB INFORMATION FUNCTIONS
* -------------------------
*/
/**
* @dev returns the status of the requested job
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @return status job's current status
*/
function getJobStatus(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee) external view returns (uint8)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
uint8 status = STATUS_JOB_NOT_EXIST;
if (jobEscrows[jobHash].exists) {
status = jobEscrows[jobHash].status;
}
return status;
}
/**
* @dev returns the date after which the Hirer can cancel the job
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @return hirerCanCancelAfter timestamp for date after which the hirer can cancel
*/
function getJobCanCancelAfter(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee) external view returns (uint32)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
uint32 hirerCanCancelAfter = 0;
if (jobEscrows[jobHash].exists) {
hirerCanCancelAfter = jobEscrows[jobHash].hirerCanCancelAfter;
}
return hirerCanCancelAfter;
}
/**
* @dev returns the number of seconds for job completion
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @return secondsToComplete number of seconds to complete job
*/
function getSecondsToComplete(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee) external view returns (uint32)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
uint32 secondsToComplete = 0;
if (jobEscrows[jobHash].exists) {
secondsToComplete = jobEscrows[jobHash].secondsToComplete;
}
return secondsToComplete;
}
/**
* @dev returns the agreed completion date of the requested job
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @return agreedCompletionDate timestamp for agreed completion date
*/
function getAgreedCompletionDate(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee) external view returns (uint32)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
uint32 agreedCompletionDate = 0;
if (jobEscrows[jobHash].exists) {
agreedCompletionDate = jobEscrows[jobHash].agreedCompletionDate;
}
return agreedCompletionDate;
}
/**
* @dev returns the actual completion date of the job of the requested job
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @return jobCompleteDate timestamp for actual completion date
*/
function getActualCompletionDate(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee) external view returns (uint32)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
uint32 jobCompleteDate = 0;
if (jobEscrows[jobHash].exists) {
jobCompleteDate = jobEscrows[jobHash].jobCompleteDate;
}
return jobCompleteDate;
}
/**
* @dev returns the value for the requested job
* Following parameters are used to regenerate the jobHash:
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @return amount job's value
*/
function getJobValue(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee) external view returns(uint256)
{
//get job Hash
bytes32 jobHash = getJobHash(
_jobId,
_hirer,
_contractor,
_value,
_fee);
uint256 amount = 0;
if (jobEscrows[jobHash].exists) {
amount = hirerEscrowMap[_hirer][jobHash];
}
return amount;
}
/**
* @dev Helper function to pre-validate mutual cancellation signatures. Used by front-end app
* to let each party know that the other has signed off the agreed %
* @param _contractorPercent percentage agreed upon
* @param _sigMsg signed message to be validated
* @param _signer wallet address of the message signer to validate against
* @return bool whether or not the signature is valid
*/
function validateRefundSignature(
uint8 _contractorPercent,
bytes _sigMsg,
address _signer) external pure returns(bool)
{
return checkRefundSignature(_contractorPercent,_sigMsg,_signer);
}
/**
* @dev Executes the actual signature verification.
* @param _contractorPercent percentage agreed upon
* @param _sigMsg signed message to be validated
* @param _signer wallet address of the message signer to validate against
* @return bool whether or not the signature is valid
*/
function checkRefundSignature(
uint8 _contractorPercent,
bytes _sigMsg,
address _signer) private pure returns(bool)
{
bytes32 percHash = keccak256(abi.encodePacked(_contractorPercent));
bytes32 msgHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",percHash));
address addr = ECRecovery.recover(msgHash,_sigMsg);
return addr == _signer;
}
/**
* @dev Generates the sha256 jobHash based on job parameters. Used in several functions
* @param _jobId The unique ID of the job, from the CoinSparrow database
* @param _hirer The wallet address of the hiring (buying) party
* @param _contractor The wallet address of the contractor (selling) party
* @param _value The ether amount being held in escrow. I.e. job cost - amount hirer is paying contractor
* @param _fee CoinSparrow fee for this job. Pre-calculated
* @return bytes32 the calculated jobHash value
*/
function getJobHash(
bytes16 _jobId,
address _hirer,
address _contractor,
uint256 _value,
uint256 _fee
) private pure returns(bytes32)
{
return keccak256(abi.encodePacked(
_jobId,
_hirer,
_contractor,
_value,
_fee));
}
} | * @dev Executes the actual signature verification. @param _contractorPercent percentage agreed upon @param _sigMsg signed message to be validated @param _signer wallet address of the message signer to validate against @return bool whether or not the signature is valid/ | function checkRefundSignature(
uint8 _contractorPercent,
bytes _sigMsg,
address _signer) private pure returns(bool)
{
bytes32 percHash = keccak256(abi.encodePacked(_contractorPercent));
bytes32 msgHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",percHash));
address addr = ECRecovery.recover(msgHash,_sigMsg);
return addr == _signer;
}
| 5,848,119 | [
1,
9763,
326,
3214,
3372,
11805,
18,
225,
389,
16351,
280,
8410,
11622,
1737,
15656,
12318,
225,
389,
7340,
3332,
6726,
883,
358,
506,
10266,
225,
389,
2977,
264,
9230,
1758,
434,
326,
883,
10363,
358,
1954,
5314,
327,
1426,
2856,
578,
486,
326,
3372,
353,
923,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
866,
21537,
5374,
12,
203,
565,
2254,
28,
389,
16351,
280,
8410,
16,
203,
565,
1731,
389,
7340,
3332,
16,
203,
565,
1758,
389,
2977,
264,
13,
3238,
16618,
1135,
12,
6430,
13,
203,
225,
288,
203,
565,
1731,
1578,
26514,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
16351,
280,
8410,
10019,
203,
565,
1731,
1578,
1234,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
3113,
457,
71,
2310,
10019,
203,
203,
565,
1758,
3091,
273,
7773,
11548,
18,
266,
3165,
12,
3576,
2310,
16,
67,
7340,
3332,
1769,
203,
565,
327,
3091,
422,
389,
2977,
264,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./IAaveInterfaces.sol";
import "./ImmutableOwnable.sol";
/**
* Single asset leveraged reborrowing strategy on AAVE, chain agnostic.
* Position managed by this contract, with full ownership and control by Owner.
* Monitor position health to avoid liquidation.
*/
contract AaveLoop is ImmutableOwnable {
using SafeERC20 for ERC20;
ERC20 public immutable ASSET; // solhint-disable-line
ILendingPool public immutable LENDING_POOL; // solhint-disable-line
IAaveIncentivesController public immutable INCENTIVES; // solhint-disable-line
/**
* @param owner The contract owner, has complete ownership, immutable
* @param asset The target underlying asset ex. USDC
* @param lendingPool The deployed AAVE ILendingPool
* @param incentives The deployed AAVE IAaveIncentivesController
*/
constructor(
address owner,
address asset,
address lendingPool,
address incentives
) ImmutableOwnable(owner) {
require(asset != address(0) && lendingPool != address(0) && incentives != address(0), "address 0");
ASSET = ERC20(asset);
LENDING_POOL = ILendingPool(lendingPool);
INCENTIVES = IAaveIncentivesController(incentives);
}
// ---- views ----
function getSupplyAndBorrowAssets() public view returns (address[] memory assets) {
DataTypes.ReserveData memory data = LENDING_POOL.getReserveData(address(ASSET));
assets = new address[](2);
assets[0] = data.aTokenAddress;
assets[1] = data.variableDebtTokenAddress;
}
/**
* @return The ASSET price in ETH according to Aave PriceOracle, used internally for all ASSET amounts calculations
*/
function getAssetPrice() public view returns (uint256) {
return IAavePriceOracle(LENDING_POOL.getAddressesProvider().getPriceOracle()).getAssetPrice(address(ASSET));
}
/**
* @return total supply balance in ASSET
*/
function getSupplyBalance() public view returns (uint256) {
(uint256 totalCollateralETH, , , , , ) = getPositionData();
return (totalCollateralETH * (10**ASSET.decimals())) / getAssetPrice();
}
/**
* @return total borrow balance in ASSET
*/
function getBorrowBalance() public view returns (uint256) {
(, uint256 totalDebtETH, , , , ) = getPositionData();
return (totalDebtETH * (10**ASSET.decimals())) / getAssetPrice();
}
/**
* @return available liquidity in ASSET
*/
function getLiquidity() public view returns (uint256) {
(, , uint256 availableBorrowsETH, , , ) = getPositionData();
return (availableBorrowsETH * (10**ASSET.decimals())) / getAssetPrice();
}
/**
* @return ASSET balanceOf(this)
*/
function getAssetBalance() public view returns (uint256) {
return ASSET.balanceOf(address(this));
}
/**
* @return Pending rewards
*/
function getPendingRewards() public view returns (uint256) {
return INCENTIVES.getRewardsBalance(getSupplyAndBorrowAssets(), address(this));
}
/**
* Position data from Aave
*/
function getPositionData()
public
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
return LENDING_POOL.getUserAccountData(address(this));
}
/**
* @return LTV of ASSET in 4 decimals ex. 82.5% == 8250
*/
function getLTV() public view returns (uint256) {
DataTypes.ReserveConfigurationMap memory config = LENDING_POOL.getConfiguration(address(ASSET));
return config.data & 0xffff; // bits 0-15 in BE
}
// ---- unrestricted ----
/**
* Claims and transfers all pending rewards to OWNER
*/
function claimRewardsToOwner() external {
INCENTIVES.claimRewards(getSupplyAndBorrowAssets(), type(uint256).max, OWNER);
}
// ---- main ----
/**
* @param iterations - Loop count
* @return Liquidity at end of the loop
*/
function enterPositionFully(uint256 iterations) external onlyOwner returns (uint256) {
return enterPosition(ASSET.balanceOf(msg.sender), iterations);
}
/**
* @param principal - ASSET transferFrom sender amount, can be 0
* @param iterations - Loop count
* @return Liquidity at end of the loop
*/
function enterPosition(uint256 principal, uint256 iterations) public onlyOwner returns (uint256) {
if (principal > 0) {
ASSET.safeTransferFrom(msg.sender, address(this), principal);
}
if (getAssetBalance() > 0) {
_supply(getAssetBalance());
}
for (uint256 i = 0; i < iterations; i++) {
_borrow(getLiquidity());
_supply(getAssetBalance());
}
return getLiquidity();
}
/**
* @param iterations - MAX loop count
* @return Withdrawn amount of ASSET to OWNER
*/
function exitPosition(uint256 iterations) external onlyOwner returns (uint256) {
(, , , , uint256 ltv, ) = getPositionData(); // 4 decimals
for (uint256 i = 0; i < iterations && getBorrowBalance() > 0; i++) {
_redeemSupply((getLiquidity() * 1e4) / ltv);
_repayBorrow(getAssetBalance());
}
if (getBorrowBalance() == 0) {
_redeemSupply(type(uint256).max);
}
return _withdrawToOwner(address(ASSET));
}
// ---- internals, public onlyOwner in case of emergency ----
/**
* amount in ASSET
*/
function _supply(uint256 amount) public onlyOwner {
ASSET.safeIncreaseAllowance(address(LENDING_POOL), amount);
LENDING_POOL.deposit(address(ASSET), amount, address(this), 0);
}
/**
* amount in ASSET
*/
function _borrow(uint256 amount) public onlyOwner {
LENDING_POOL.borrow(address(ASSET), amount, 2, 0, address(this));
}
/**
* amount in ASSET
*/
function _redeemSupply(uint256 amount) public onlyOwner {
LENDING_POOL.withdraw(address(ASSET), amount, address(this));
}
/**
* amount in ASSET
*/
function _repayBorrow(uint256 amount) public onlyOwner {
ASSET.safeIncreaseAllowance(address(LENDING_POOL), amount);
LENDING_POOL.repay(address(ASSET), amount, 2, address(this));
}
function _withdrawToOwner(address asset) public onlyOwner returns (uint256) {
uint256 balance = ERC20(asset).balanceOf(address(this));
ERC20(asset).safeTransfer(OWNER, balance);
return balance;
}
// ---- emergency ----
function emergencyFunctionCall(address target, bytes memory data) external onlyOwner {
Address.functionCall(target, data);
}
function emergencyFunctionDelegateCall(address target, bytes memory data) external onlyOwner {
Address.functionDelegateCall(target, data);
}
}
| * @param principal - ASSET transferFrom sender amount, can be 0 @param iterations - Loop count @return Liquidity at end of the loop/ | function enterPosition(uint256 principal, uint256 iterations) public onlyOwner returns (uint256) {
if (principal > 0) {
ASSET.safeTransferFrom(msg.sender, address(this), principal);
}
if (getAssetBalance() > 0) {
_supply(getAssetBalance());
}
for (uint256 i = 0; i < iterations; i++) {
_borrow(getLiquidity());
_supply(getAssetBalance());
}
return getLiquidity();
}
| 1,013,537 | [
1,
26138,
300,
5355,
4043,
7412,
1265,
5793,
3844,
16,
848,
506,
374,
225,
11316,
300,
9720,
1056,
327,
511,
18988,
24237,
622,
679,
434,
326,
2798,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6103,
2555,
12,
11890,
5034,
8897,
16,
2254,
5034,
11316,
13,
1071,
1338,
5541,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
26138,
405,
374,
13,
288,
203,
5411,
5355,
4043,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
8897,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
588,
6672,
13937,
1435,
405,
374,
13,
288,
203,
5411,
389,
2859,
1283,
12,
588,
6672,
13937,
10663,
203,
3639,
289,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
11316,
31,
277,
27245,
288,
203,
5411,
389,
70,
15318,
12,
588,
48,
18988,
24237,
10663,
203,
5411,
389,
2859,
1283,
12,
588,
6672,
13937,
10663,
203,
3639,
289,
203,
203,
3639,
327,
9014,
18988,
24237,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IOnchainVaults.sol";
import "./interfaces/IOrderRegistry.sol";
import "./interfaces/IShareToken.sol";
import "./interfaces/IStrategyPool.sol";
/**
* @title common broker
*/
contract Broker is Ownable {
using Address for address;
using SafeERC20 for IERC20;
event PriceChanged(uint256 rideId, uint256 oldVal, uint256 newVal);
event SlippageChanged(uint256 rideId, uint256 oldVal, uint256 newVal);
event RideInfoRegistered(uint256 rideId, RideInfo rideInfo);
event MintAndSell(uint256 rideId, uint256 mintShareAmt, uint256 price, uint256 slippage);
event CancelSell(uint256 rideId, uint256 cancelShareAmt);
event RideDeparted(uint256 rideId, uint256 usedInputTokenAmt);
event SharesBurned(uint256 rideId, uint256 burnedShareAmt);
event SharesRedeemed(uint256 rideId, uint256 redeemedShareAmt);
event OnchainVaultsChanged(address oldAddr, address newAddr);
address public onchainVaults;
mapping (uint256=>uint256) public prices; // rideid=>price, price in decimal 1e18
uint256 public constant PRICE_DECIMALS = 1e18;
mapping (uint256=>uint256) public slippages; // rideid=>slippage, slippage in denominator 10000
uint256 public constant SLIPPAGE_DENOMINATOR = 10000;
bytes4 internal constant ERC20_SELECTOR = bytes4(keccak256("ERC20Token(address)"));
bytes4 internal constant ETH_SELECTOR = bytes4(keccak256("ETH()"));
uint256 internal constant SELECTOR_OFFSET = 0x20;
// Starkex token id of this mint token
struct RideInfo {
address share;
uint256 tokenIdShare;
uint256 quantumShare;
address inputToken;
uint256 tokenIdInput;
uint256 quantumInput;
address outputToken;
uint256 tokenIdOutput;
uint256 quantumOutput;
address strategyPool; // 3rd defi pool
}
// rideid => RideInfo
// rideId will also be used as vaultIdShare, vaultIdInput and vaultIdOutput,
// this is easy to maintain and will assure funds from different rides won’t mix together and create weird edge cases
mapping (uint256 => RideInfo) public rideInfos;
mapping (uint256=>uint256) public ridesShares; // rideid=>amount
mapping (uint256=>bool) public rideDeparted; // rideid=>bool
uint256 public nonce;
uint256 public constant EXP_TIME = 2e6; // expiration time stamp of the limit order
mapping (uint256=>uint256) public actualPrices; //rideid=>actual price
struct OrderAssetInfo {
uint256 tokenId;
uint256 quantizedAmt;
uint256 vaultId;
}
/**
* @dev Constructor
*/
constructor(
address _onchainVaults
) {
onchainVaults = _onchainVaults;
}
/**
* @notice can be set multiple times, will use latest when mintShareAndSell.
*/
function setPrice(uint256 _rideId, uint256 _price) external onlyOwner {
require(ridesShares[_rideId] == 0, "change forbidden once share starting to sell");
uint256 oldVal = prices[_rideId];
prices[_rideId] = _price;
emit PriceChanged(_rideId, oldVal, _price);
}
/**
* @notice price slippage allowance when executing strategy
*/
function setSlippage(uint256 _rideId, uint256 _slippage) external onlyOwner {
require(_slippage <= 10000, "invalid slippage");
require(ridesShares[_rideId] == 0, "change forbidden once share starting to sell");
uint256 oldVal = slippages[_rideId];
slippages[_rideId] = _slippage;
emit SlippageChanged(_rideId, oldVal, _slippage);
}
/**
* @notice registers ride info
*/
function addRideInfo(uint256 _rideId, uint256[3] memory _tokenIds, address[3] memory _tokens, address _strategyPool) external onlyOwner {
RideInfo memory rideInfo = rideInfos[_rideId];
require(rideInfo.tokenIdInput == 0, "ride assets info registered already");
require(_strategyPool.isContract(), "invalid strategy pool addr");
_checkValidTokenIdAndAddr(_tokenIds[0], _tokens[0]);
_checkValidTokenIdAndAddr(_tokenIds[1], _tokens[1]);
_checkValidTokenIdAndAddr(_tokenIds[2], _tokens[2]);
IOnchainVaults ocv = IOnchainVaults(onchainVaults);
uint256 quantumShare = ocv.getQuantum(_tokenIds[0]);
uint256 quantumInput = ocv.getQuantum(_tokenIds[1]);
uint256 quantumOutput = ocv.getQuantum(_tokenIds[2]);
rideInfo = RideInfo(_tokens[0], _tokenIds[0], quantumShare, _tokens[1], _tokenIds[1],
quantumInput, _tokens[2], _tokenIds[2], quantumOutput, _strategyPool);
rideInfos[_rideId] = rideInfo;
emit RideInfoRegistered(_rideId, rideInfo);
}
/**
* @notice mint share and sell for input token
*/
function mintShareAndSell(uint256 _rideId, uint256 _amount, uint256 _tokenIdFee, uint256 _quantizedAmtFee, uint256 _vaultIdFee) external onlyOwner {
RideInfo memory rideInfo = rideInfos[_rideId];
require(rideInfo.tokenIdInput != 0, "ride assets info not registered");
require(prices[_rideId] != 0, "price not set");
require(slippages[_rideId] != 0, "slippage not set");
require(ridesShares[_rideId] == 0, "already mint for this ride");
if (_tokenIdFee != 0) {
_checkValidTokenId(_tokenIdFee);
}
IShareToken(rideInfo.share).mint(address(this), _amount);
IERC20(rideInfo.share).safeIncreaseAllowance(onchainVaults, _amount);
IOnchainVaults(onchainVaults).depositERC20ToVault(rideInfo.tokenIdShare, _rideId, _amount / rideInfo.quantumShare);
_submitOrder(OrderAssetInfo(rideInfo.tokenIdShare, _amount / rideInfo.quantumShare, _rideId),
OrderAssetInfo(rideInfo.tokenIdInput, _amount / rideInfo.quantumInput, _rideId), OrderAssetInfo(_tokenIdFee, _quantizedAmtFee, _vaultIdFee));
ridesShares[_rideId] = _amount;
emit MintAndSell(_rideId, _amount, prices[_rideId], slippages[_rideId]);
}
/**
* @notice cancel selling for input token
*/
function cancelSell(uint256 _rideId, uint256 _tokenIdFee, uint256 _quantizedAmtFee, uint256 _vaultIdFee) external onlyOwner {
uint256 amount = ridesShares[_rideId];
require(amount > 0, "no shares to cancel sell");
require(!rideDeparted[_rideId], "ride departed already");
if (_tokenIdFee != 0) {
_checkValidTokenId(_tokenIdFee);
}
RideInfo memory rideInfo = rideInfos[_rideId]; //amount > 0 implies that the rideAssetsInfo already registered
_submitOrder(OrderAssetInfo(rideInfo.tokenIdInput, amount / rideInfo.quantumInput, _rideId),
OrderAssetInfo(rideInfo.tokenIdShare, amount / rideInfo.quantumShare, _rideId), OrderAssetInfo(_tokenIdFee, _quantizedAmtFee, _vaultIdFee));
emit CancelSell(_rideId, amount);
}
/**
* @notice ride departure to execute strategy (swap input token for output token)
* share : inputtoken = 1 : 1, outputtoken : share = price
*/
function departRide(uint256 _rideId, uint256 _tokenIdFee, uint256 _quantizedAmtFee, uint256 _vaultIdFee) external onlyOwner {
require(!rideDeparted[_rideId], "ride departed already");
if (_tokenIdFee != 0) {
_checkValidTokenId(_tokenIdFee);
}
rideDeparted[_rideId] = true;
burnRideShares(_rideId); //burn unsold shares
uint256 amount = ridesShares[_rideId]; //get the left share amount
require(amount > 0, "no shares to depart");
RideInfo memory rideInfo = rideInfos[_rideId]; //amount > 0 implies that the rideAssetsInfo already registered
IOnchainVaults ocv = IOnchainVaults(onchainVaults);
uint256 inputTokenAmt;
{
uint256 inputTokenQuantizedAmt = ocv.getQuantizedVaultBalance(address(this), rideInfo.tokenIdInput, _rideId);
assert(inputTokenQuantizedAmt > 0);
ocv.withdrawFromVault(rideInfo.tokenIdInput, _rideId, inputTokenQuantizedAmt);
inputTokenAmt = inputTokenQuantizedAmt * rideInfo.quantumInput;
}
uint256 outputAmt;
if (rideInfo.inputToken == address(0) /*ETH*/) {
outputAmt = IStrategyPool(rideInfo.strategyPool).sellEth{value: inputTokenAmt}(rideInfo.outputToken);
} else {
IERC20(rideInfo.inputToken).safeIncreaseAllowance(rideInfo.strategyPool, inputTokenAmt);
outputAmt = IStrategyPool(rideInfo.strategyPool).sellErc(rideInfo.inputToken, rideInfo.outputToken, inputTokenAmt);
}
{
uint256 expectMinResult = amount * prices[_rideId] * (SLIPPAGE_DENOMINATOR - slippages[_rideId]) / PRICE_DECIMALS / SLIPPAGE_DENOMINATOR;
require(outputAmt >= expectMinResult, "price and slippage not fulfilled");
actualPrices[_rideId] = outputAmt * PRICE_DECIMALS / amount;
if (rideInfo.outputToken != address(0) /*ERC20*/) {
IERC20(rideInfo.outputToken).safeIncreaseAllowance(onchainVaults, outputAmt);
ocv.depositERC20ToVault(rideInfo.tokenIdOutput, _rideId, outputAmt / rideInfo.quantumOutput);
} else {
ocv.depositEthToVault{value: outputAmt / rideInfo.quantumOutput}(rideInfo.tokenIdOutput, _rideId);
}
}
_submitOrder(OrderAssetInfo(rideInfo.tokenIdOutput, outputAmt / rideInfo.quantumOutput, _rideId),
OrderAssetInfo(rideInfo.tokenIdShare, amount / rideInfo.quantumShare, _rideId), OrderAssetInfo(_tokenIdFee, _quantizedAmtFee, _vaultIdFee));
emit RideDeparted(_rideId, inputTokenAmt);
}
/**
* @notice burn ride shares after ride is done
*/
function burnRideShares(uint256 _rideId) public onlyOwner {
uint256 amount = ridesShares[_rideId];
require(amount > 0, "no shares to burn");
RideInfo memory rideInfo = rideInfos[_rideId]; //amount > 0 implies that the rideAssetsInfo already registered
IOnchainVaults ocv = IOnchainVaults(onchainVaults);
uint256 quantizedAmountToBurn = ocv.getQuantizedVaultBalance(address(this), rideInfo.tokenIdShare, _rideId);
require(quantizedAmountToBurn > 0, "no shares to burn");
ocv.withdrawFromVault(rideInfo.tokenIdShare, _rideId, quantizedAmountToBurn);
uint256 burnAmt = quantizedAmountToBurn * rideInfo.quantumShare;
ridesShares[_rideId] = amount - burnAmt; // update to left amount
IShareToken(rideInfo.share).burn(address(this), burnAmt);
emit SharesBurned(_rideId, burnAmt);
}
/**
* @notice user to redeem share for input or output token
* input token when ride has not been departed, otherwise, output token
*/
function redeemShare(uint256 _rideId, uint256 _redeemAmount) external {
uint256 amount = ridesShares[_rideId];
require(amount > 0, "no shares to redeem");
RideInfo memory rideInfo = rideInfos[_rideId]; //amount > 0 implies that the rideAssetsInfo already registered
IERC20(rideInfo.share).safeTransferFrom(msg.sender, address(this), _redeemAmount);
IOnchainVaults ocv = IOnchainVaults(onchainVaults);
bool departed = rideDeparted[_rideId];
if (departed) {
//swap to output token
uint256 boughtAmt = _redeemAmount * actualPrices[_rideId] / PRICE_DECIMALS;
ocv.withdrawFromVault(rideInfo.tokenIdOutput, _rideId, boughtAmt / rideInfo.quantumOutput);
IERC20(rideInfo.outputToken).safeTransfer(msg.sender, boughtAmt);
} else {
//swap to input token
ocv.withdrawFromVault(rideInfo.tokenIdInput, _rideId, _redeemAmount / rideInfo.quantumInput);
if (rideInfo.inputToken == address(0) /*ETH*/) {
(bool success, ) = msg.sender.call{value: _redeemAmount}("");
require(success, "ETH_TRANSFER_FAILED");
} else {
IERC20(rideInfo.inputToken).safeTransfer(msg.sender, _redeemAmount);
}
}
ridesShares[_rideId] -= _redeemAmount;
IShareToken(rideInfo.share).burn(address(this), _redeemAmount);
emit SharesRedeemed(_rideId, _redeemAmount);
}
function _checkValidTokenIdAndAddr(uint256 tokenId, address token) view internal {
bytes4 selector = _checkValidTokenId(tokenId);
if (selector == ETH_SELECTOR) {
require(token == address(0), "ETH addr should be 0");
} else if (selector == ERC20_SELECTOR) {
require(token.isContract(), "invalid token addr");
}
}
function _checkValidTokenId(uint256 tokenId) view internal returns (bytes4 selector) {
selector = extractTokenSelector(IOnchainVaults(onchainVaults).getAssetInfo(tokenId));
require(selector == ETH_SELECTOR || selector == ERC20_SELECTOR, "unsupported token");
}
function extractTokenSelector(bytes memory assetInfo)
internal
pure
returns (bytes4 selector)
{
assembly {
selector := and(
0xffffffff00000000000000000000000000000000000000000000000000000000,
mload(add(assetInfo, SELECTOR_OFFSET))
)
}
}
function _submitOrder(OrderAssetInfo memory sellInfo, OrderAssetInfo memory buyInfo, OrderAssetInfo memory feeInfo) private {
nonce += 1;
address orderRegistryAddr = IOnchainVaults(onchainVaults).orderRegistryAddress();
IOrderRegistry(orderRegistryAddr).registerLimitOrder(onchainVaults, sellInfo.tokenId, buyInfo.tokenId, feeInfo.tokenId,
sellInfo.quantizedAmt, buyInfo.quantizedAmt, feeInfo.quantizedAmt, sellInfo.vaultId, buyInfo.vaultId, feeInfo.vaultId, nonce, EXP_TIME);
}
function setOnchainVaults(address _newAddr) external onlyOwner {
emit OnchainVaultsChanged(onchainVaults, _newAddr);
onchainVaults = _newAddr;
}
// To receive ETH when invoking IOnchainVaults.withdrawFromVault
receive() external payable {}
fallback() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface IOnchainVaults {
function depositERC20ToVault(
uint256 assetId,
uint256 vaultId,
uint256 quantizedAmount
) external;
function depositEthToVault(
uint256 assetId,
uint256 vaultId)
external payable;
function withdrawFromVault(
uint256 assetId,
uint256 vaultId,
uint256 quantizedAmount
) external;
function getQuantizedVaultBalance(
address ethKey,
uint256 assetId,
uint256 vaultId
) external view returns (uint256);
function getVaultBalance(
address ethKey,
uint256 assetId,
uint256 vaultId
) external view returns (uint256);
function getQuantum(uint256 presumedAssetType) external view returns (uint256);
function orderRegistryAddress() external view returns (address);
function isAssetRegistered(uint256 assetType) external view returns (bool);
function getAssetInfo(uint256 assetType) external view returns (bytes memory assetInfo);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface IOrderRegistry {
function registerLimitOrder(
address exchangeAddress,
uint256 tokenIdSell,
uint256 tokenIdBuy,
uint256 tokenIdFee,
uint256 amountSell,
uint256 amountBuy,
uint256 amountFee,
uint256 vaultIdSell,
uint256 vaultIdBuy,
uint256 vaultIdFee,
uint256 nonce,
uint256 expirationTimestamp
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
interface IShareToken {
function mint(address _to, uint256 _amount) external;
function burn(address _from, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
interface IStrategyPool {
// sell the amount of the input token, and the amount of output token will be sent to msg.sender
function sellErc(address inputToken, address outputToken, uint256 inputAmt) external returns (uint256 outputAmt);
function sellEth(address outputToken) external payable returns (uint256 outputAmt);
}
// 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/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/IStrategyPool.sol";
import "./interfaces/IDummyToken.sol";
/**
* @title Dummy pool
*/
contract StrategyDummy is IStrategyPool, Ownable {
using SafeERC20 for IERC20;
address public broker;
modifier onlyBroker() {
require(msg.sender == broker, "caller is not broker");
_;
}
event BrokerUpdated(address broker);
event OutputTokensUpdated(address wrapToken, bool enabled);
mapping(address => bool) public supportedOutputTokens;
constructor(
address _broker
) {
broker = _broker;
}
function sellErc(address inputToken, address outputToken, uint256 inputAmt) external onlyBroker returns (uint256 outputAmt) {
bool toBuy = supportedOutputTokens[outputToken];
bool toSell = supportedOutputTokens[inputToken];
require(toBuy || toSell, "not supported tokens!");
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmt);
if (toBuy) {
IERC20(inputToken).safeIncreaseAllowance(outputToken, inputAmt);
IDummyToken(outputToken).buy(inputAmt);
outputAmt = IERC20(outputToken).balanceOf(address(this));
IERC20(outputToken).safeTransfer(msg.sender, outputAmt);
} else {
IDummyToken(inputToken).sell(inputAmt);
outputAmt = IERC20(outputToken).balanceOf(address(this));
IERC20(outputToken).safeTransfer(msg.sender, outputAmt);
}
}
function sellEth(address outputToken) external onlyBroker payable returns (uint256 outputAmt) {
// do nothing
}
function updateBroker(address _broker) external onlyOwner {
broker = _broker;
emit BrokerUpdated(broker);
}
function setSupportedOutputToken(address _outputToken, bool _enabled) external onlyOwner {
supportedOutputTokens[_outputToken] = _enabled;
emit OutputTokensUpdated(_outputToken, _enabled);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface IDummyToken {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function mint(address _to, uint _amount) external;
function buy(uint _amount) external;
function sell(uint _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IDummyToken.sol";
/**
* @title Dummy output token
*/
contract OutputTokenDummy is ERC20, Ownable {
using SafeERC20 for IERC20;
uint8 private immutable _decimals;
address private supplyToken;
uint256 private lastHarvestBlockNum;
uint256 public harvestPerBlock;
address public controller; // st comp
modifier onlyController() {
require(msg.sender == controller, "caller is not controller");
_;
}
event ControllerUpdated(address controller);
constructor(
address _supplyToken,
address _controller,
uint256 _harvestPerBlock
) ERC20(string(abi.encodePacked("Celer ", IDummyToken(_supplyToken).name())), string(abi.encodePacked("celr", IDummyToken(_supplyToken).symbol()))) {
_decimals = IDummyToken(_supplyToken).decimals();
supplyToken = _supplyToken;
controller = _controller;
lastHarvestBlockNum = block.number;
harvestPerBlock = _harvestPerBlock;
}
function buy(uint _amount) external onlyController {
require(_amount > 0, "invalid amount");
IERC20(supplyToken).safeTransferFrom(msg.sender, address(this), _amount);
_mint(msg.sender, _amount);
}
function sell(uint _amount) external {
require(_amount > 0, "invalid amount");
require(totalSupply() >= _amount, "not enough supply");
IDummyToken(supplyToken).mint(address(this), harvestPerBlock * (block.number - lastHarvestBlockNum));
lastHarvestBlockNum = block.number;
IERC20(supplyToken).safeTransfer(msg.sender, _amount * IERC20(supplyToken).balanceOf(address(this)) / totalSupply());
_burn(msg.sender, _amount);
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function underlyingToken() public view returns (address) {
return supplyToken;
}
function updateController(address _controller) external onlyOwner {
controller = _controller;
emit ControllerUpdated(_controller);
}
function updateHarvestPerBlock(uint256 newVal) external onlyOwner {
harvestPerBlock = newVal;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/ICErc20.sol";
import "./interfaces/IComptroller.sol";
/**
* @title Wrapped Token of compound c tokens
*/
contract WrappedToken is ERC20, Ownable {
using Address for address;
using SafeERC20 for IERC20;
uint8 private immutable _decimals;
address private immutable ctoken;
address public immutable comp; // compound comp token
address public immutable comptroller; //compound controller
address public controller; // st comp
modifier onlyController() {
require(msg.sender == controller, "caller is not controller");
_;
}
modifier onlyEOA() {
require(msg.sender == tx.origin && !address(msg.sender).isContract(), "Not EOA");
_;
}
event ControllerUpdated(address controller);
constructor(
address _ctoken,
address _controller,
address _comptroller,
address _comp
) ERC20(string(abi.encodePacked("Wrapped ", ICErc20(_ctoken).name())), string(abi.encodePacked("W", ICErc20(_ctoken).symbol()))) {
_decimals = ICErc20(_ctoken).decimals();
ctoken = _ctoken;
controller = _controller;
comptroller = _comptroller;
comp = _comp;
}
function mint(uint _amount) external onlyController {
require(_amount > 0, "invalid amount");
IERC20(ctoken).safeTransferFrom(msg.sender, address(this), _amount);
_mint(msg.sender, _amount);
}
function burn(uint _amount) external {
require(_amount > 0, "invalid amount");
require(totalSupply() >= _amount, "not enough supply");
// distribute harvested comp proportional
uint256 compBalance = IERC20(comp).balanceOf(address(this));
if (compBalance > 0) {
IERC20(comp).safeTransfer(msg.sender, compBalance * _amount / totalSupply());
}
_burn(msg.sender, _amount);
IERC20(ctoken).safeTransfer(msg.sender, _amount);
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function underlyingCToken() public view returns (address) {
return ctoken;
}
function harvest() external onlyEOA {
// Claim COMP token.
IComptroller(comptroller).claimComp(address(this));
}
function updateController(address _controller) external onlyOwner {
controller = _controller;
emit ControllerUpdated(_controller);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface ICErc20 {
/**
* @notice Accrue interest for `owner` and return the underlying balance.
*
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint256);
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @notice Supply ERC20 token to the market, receive cTokens in exchange.
*
* @param mintAmount The amount of the underlying asset to supply
* @return 0 = success, otherwise a failure
*/
function mint(uint256 mintAmount) external returns (uint256);
/**
* @notice Redeem cTokens in exchange for a specified amount of underlying asset.
*
* @param redeemAmount The amount of underlying to redeem
* @return 0 = success, otherwise a failure
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint256 redeemTokens) external returns (uint256);
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint256);
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() external returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address dst, uint256 amount) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./ICErc20.sol";
interface IComptroller {
/**
* @notice Claim all the comp accrued by the holder in all markets.
*
* @param holder The address to claim COMP for
*/
function claimComp(address holder) external;
/**
* @notice Claim all comp accrued by the holders
* @param holders The addresses to claim COMP for
* @param cTokens The list of markets to claim COMP in
* @param borrowers Whether or not to claim COMP earned by borrowing
* @param suppliers Whether or not to claim COMP earned by supplying
*/
function claimComp(
address[] memory holders,
ICErc20[] memory cTokens,
bool borrowers,
bool suppliers
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/ICErc20.sol";
import "./interfaces/ICEth.sol";
import "./interfaces/IWrappedToken.sol";
import "./interfaces/IUniswapV2Router02.sol";
import "../../interfaces/IStrategyPool.sol";
/**
* @title Compound pool
*/
contract StrategyCompound is IStrategyPool, Ownable {
using SafeERC20 for IERC20;
address public broker;
modifier onlyBroker() {
require(msg.sender == broker, "caller is not broker");
_;
}
address public immutable comp; // compound comp token
address public immutable uniswap; // The address of the Uniswap V2 router
address public immutable weth; // The address of WETH token
event BrokerUpdated(address broker);
event WrapTokenUpdated(address wrapToken, bool enabled);
mapping(address => bool) public supportedWrapTokens; //wrappedtoken => true
constructor(
address _broker,
address _comp,
address _uniswap,
address _weth
) {
broker = _broker;
comp = _comp;
uniswap = _uniswap;
weth = _weth;
}
function sellErc(address inputToken, address outputToken, uint256 inputAmt) external onlyBroker returns (uint256 outputAmt) {
bool toBuy = supportedWrapTokens[outputToken];
bool toSell = supportedWrapTokens[inputToken];
require(toBuy || toSell, "not supported tokens!");
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmt);
if (toBuy) { // to buy a wrapped token
address cToken = IWrappedToken(outputToken).underlyingCToken();
IERC20(inputToken).safeIncreaseAllowance(cToken, inputAmt);
uint256 mintResult = ICErc20(cToken).mint(inputAmt);
require(mintResult == 0, "Couldn't mint cToken");
outputAmt = ICErc20(cToken).balanceOf(address(this));
// transfer cToken into wrapped token contract and mint equal wrapped tokens
IERC20(cToken).safeIncreaseAllowance(outputToken, outputAmt);
IWrappedToken(outputToken).mint(outputAmt);
IERC20(outputToken).safeTransfer(msg.sender, outputAmt);
} else { // to sell a wrapped token
address cToken = IWrappedToken(inputToken).underlyingCToken();
// transfer cToken/comp from wrapped token contract and burn the wrapped tokens
IWrappedToken(inputToken).burn(inputAmt);
uint256 redeemResult = ICErc20(cToken).redeem(inputAmt);
require(redeemResult == 0, "Couldn't redeem cToken");
if (outputToken != address(0) /*ERC20*/) {
sellCompForErc(outputToken);
outputAmt = IERC20(outputToken).balanceOf(address(this));
IERC20(outputToken).safeTransfer(msg.sender, outputAmt);
} else /*ETH*/ {
sellCompForEth();
outputAmt = address(this).balance;
(bool success, ) = msg.sender.call{value: outputAmt}(""); // NOLINT: low-level-calls.
require(success, "eth transfer failed");
}
}
}
function sellCompForErc(address target) private {
uint256 compBalance = IERC20(comp).balanceOf(address(this));
if (compBalance > 0) {
// Sell COMP token for obtain more supplying token(e.g. DAI, USDT)
IERC20(comp).safeIncreaseAllowance(uniswap, compBalance);
address[] memory paths = new address[](3);
paths[0] = comp;
paths[1] = weth;
paths[2] = target;
IUniswapV2Router02(uniswap).swapExactTokensForTokens(
compBalance,
uint256(0),
paths,
address(this),
block.timestamp + 1800
);
}
}
function sellCompForEth() private {
uint256 compBalance = IERC20(comp).balanceOf(address(this));
if (compBalance > 0) {
// Sell COMP token for obtain more ETH
IERC20(comp).safeIncreaseAllowance(uniswap, compBalance);
address[] memory paths = new address[](1);
paths[0] = comp;
IUniswapV2Router02(uniswap).swapExactTokensForETH(
compBalance,
uint256(0),
paths,
address(this),
block.timestamp + 1800
);
}
}
function sellEth(address outputToken) external onlyBroker payable returns (uint256 outputAmt) {
require(supportedWrapTokens[outputToken], "not supported tokens!");
address cToken = IWrappedToken(outputToken).underlyingCToken();
ICEth(cToken).mint{value: msg.value}();
outputAmt = ICEth(cToken).balanceOf(address(this));
// transfer cToken into wrapped token contract and mint equal wrapped tokens
IERC20(cToken).safeIncreaseAllowance(outputToken, outputAmt);
IWrappedToken(outputToken).mint(outputAmt);
IERC20(outputToken).safeTransfer(msg.sender, outputAmt);
}
function updateBroker(address _broker) external onlyOwner {
broker = _broker;
emit BrokerUpdated(broker);
}
function setSupportedWrapToken(address _wrapToken, bool _enabled) external onlyOwner {
supportedWrapTokens[_wrapToken] = _enabled;
emit WrapTokenUpdated(_wrapToken, _enabled);
}
receive() external payable {}
fallback() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface ICEth {
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @notice Accrue interest for `owner` and return the underlying balance.
*
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint256);
/**
* @notice Supply ETH to the market, receive cTokens in exchange.
*/
function mint() external payable;
/**
* @notice Redeem cTokens in exchange for a specified amount of underlying asset.
*
* @param redeemAmount The amount of underlying to redeem
* @return 0 = success, otherwise a failure
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() external returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface IWrappedToken {
function mint(uint _amount) external;
function burn(uint _amount) external;
function underlyingCToken() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.9;
interface IUniswapV2Router02 {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata paths,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
/**
* @title A mintable {ERC20} token.
*/
contract InputTokenDummy is ERC20Burnable, Ownable {
uint8 private _decimals;
/**
* @dev Constructor that gives msg.sender an initial supply of tokens.
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initialSupply_
) ERC20(name_, symbol_) {
_decimals = decimals_;
_mint(msg.sender, initialSupply_);
}
/**
* @dev Creates `amount` new tokens for `to`.
*/
function mint(address to, uint256 amount) public {
_mint(to, amount);
}
function decimals() public view override returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract 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);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./interfaces/IShareToken.sol";
/**
* @title A {ERC20} token used for ride share.
*/
contract ShareToken is IShareToken, ERC20, Ownable {
uint8 private immutable _decimals;
address public broker;
modifier onlyBroker() {
require(msg.sender == broker, "caller is not broker");
_;
}
event BrokerUpdated(address broker);
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
address _broker
) ERC20(name_, symbol_) {
_decimals = decimals_;
broker = _broker;
}
function mint(address _to, uint256 _amount) external onlyBroker {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amount) external onlyBroker {
_burn(_from, _amount);
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function updateBroker(address _broker) external onlyOwner {
broker = _broker;
emit BrokerUpdated(broker);
}
} | transfer cToken into wrapped token contract and mint equal wrapped tokens | function sellEth(address outputToken) external onlyBroker payable returns (uint256 outputAmt) {
require(supportedWrapTokens[outputToken], "not supported tokens!");
address cToken = IWrappedToken(outputToken).underlyingCToken();
outputAmt = ICEth(cToken).balanceOf(address(this));
IERC20(cToken).safeIncreaseAllowance(outputToken, outputAmt);
IWrappedToken(outputToken).mint(outputAmt);
IERC20(outputToken).safeTransfer(msg.sender, outputAmt);
ICEth(cToken).mint{value: msg.value}();
}
| 54,268 | [
1,
13866,
276,
1345,
1368,
5805,
1147,
6835,
471,
312,
474,
3959,
5805,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
357,
80,
41,
451,
12,
2867,
876,
1345,
13,
3903,
1338,
11194,
8843,
429,
1135,
261,
11890,
5034,
876,
31787,
13,
288,
203,
3639,
2583,
12,
4127,
2964,
5157,
63,
2844,
1345,
6487,
315,
902,
3260,
2430,
4442,
1769,
203,
540,
203,
3639,
1758,
276,
1345,
273,
467,
17665,
1345,
12,
2844,
1345,
2934,
9341,
6291,
1268,
969,
5621,
203,
3639,
876,
31787,
273,
467,
1441,
451,
12,
71,
1345,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
467,
654,
39,
3462,
12,
71,
1345,
2934,
4626,
382,
11908,
7009,
1359,
12,
2844,
1345,
16,
876,
31787,
1769,
203,
3639,
467,
17665,
1345,
12,
2844,
1345,
2934,
81,
474,
12,
2844,
31787,
1769,
203,
203,
3639,
467,
654,
39,
3462,
12,
2844,
1345,
2934,
4626,
5912,
12,
3576,
18,
15330,
16,
876,
31787,
1769,
203,
3639,
467,
1441,
451,
12,
71,
1345,
2934,
81,
474,
95,
1132,
30,
1234,
18,
1132,
97,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/9001/0x110DD7887321f24477BF4A135a1E5eB7Bf31691a/sources/contracts/StreamingBoundHedgeys.sol | * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension/ | interface IERC721Delegate is IERC721, IERC721Enumerable {
function balanceOfDelegate(address delegate) external view returns (uint256);
function delegatedTo(uint256 tokenId) external view returns (address);
function tokenOfDelegateByIndex(address delegate, uint256 index) external view returns (uint256);
}
}
| 11,531,850 | [
1,
654,
39,
17,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
16,
3129,
16836,
2710,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
654,
39,
27,
5340,
9586,
353,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
3572,
25121,
288,
203,
225,
445,
11013,
951,
9586,
12,
2867,
7152,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
30055,
774,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
225,
445,
1147,
951,
9586,
21268,
12,
2867,
7152,
16,
2254,
5034,
770,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
97,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "../external/ERC721PresetMinterPauserAutoId.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/ISeniorPool.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../library/StakingRewardsVesting.sol";
contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20withDec;
using ConfigHelper for GoldfinchConfig;
using StakingRewardsVesting for StakingRewardsVesting.Rewards;
enum LockupPeriod {
SixMonths,
TwelveMonths,
TwentyFourMonths
}
struct StakedPosition {
// @notice Staked amount denominated in `stakingToken().decimals()`
uint256 amount;
// @notice Struct describing rewards owed with vesting
StakingRewardsVesting.Rewards rewards;
// @notice Multiplier applied to staked amount when locking up position
uint256 leverageMultiplier;
// @notice Time in seconds after which position can be unstaked
uint256 lockedUntil;
}
/* ========== EVENTS =================== */
event RewardsParametersUpdated(
address indexed who,
uint256 targetCapacity,
uint256 minRate,
uint256 maxRate,
uint256 minRateAtPercent,
uint256 maxRateAtPercent
);
event TargetCapacityUpdated(address indexed who, uint256 targetCapacity);
event VestingScheduleUpdated(address indexed who, uint256 vestingLength);
event MinRateUpdated(address indexed who, uint256 minRate);
event MaxRateUpdated(address indexed who, uint256 maxRate);
event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent);
event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent);
event LeverageMultiplierUpdated(address indexed who, LockupPeriod lockupPeriod, uint256 leverageMultiplier);
/* ========== STATE VARIABLES ========== */
uint256 private constant MULTIPLIER_DECIMALS = 1e18;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
/// @notice The block timestamp when rewards were last checkpointed
uint256 public lastUpdateTime;
/// @notice Accumulated rewards per token at the last checkpoint
uint256 public accumulatedRewardsPerToken;
/// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()`
uint256 public rewardsAvailable;
/// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint
mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken;
/// @notice Desired supply of staked tokens. The reward rate adjusts in a range
/// around this value to incentivize staking or unstaking to maintain it.
uint256 public targetCapacity;
/// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public minRate;
/// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public maxRate;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public maxRateAtPercent;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public minRateAtPercent;
/// @notice The duration in seconds over which rewards vest
uint256 public vestingLength;
/// @dev Supply of staked tokens, excluding leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 public totalStakedSupply;
/// @dev Supply of staked tokens, including leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 private totalLeveragedStakedSupply;
/// @dev A mapping from lockup periods to leverage multipliers used to boost rewards.
/// See `stakeWithLockup`.
mapping(LockupPeriod => uint256) private leverageMultipliers;
/// @dev NFT tokenId => staked position
mapping(uint256 => StakedPosition) public positions;
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS");
__ERC721Pausable_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
config = _config;
vestingLength = 365 days;
// Set defaults for leverage multipliers (no boosting)
leverageMultipliers[LockupPeriod.SixMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwelveMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwentyFourMonths] = MULTIPLIER_DECIMALS; // 1x
}
/* ========== VIEWS ========== */
/// @notice Returns the staked balance of a given position token
/// @param tokenId A staking position token ID
/// @return Amount of staked tokens denominated in `stakingToken().decimals()`
function stakedBalanceOf(uint256 tokenId) external view returns (uint256) {
return positions[tokenId].amount;
}
/// @notice The address of the token being disbursed as rewards
function rewardsToken() public view returns (IERC20withDec) {
return config.getGFI();
}
/// @notice The address of the token that can be staked
function stakingToken() public view returns (IERC20withDec) {
return config.getFidu();
}
/// @notice The additional rewards earned per token, between the provided time and the last
/// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited
/// by the amount of rewards that are available for distribution; if there aren't enough
/// rewards in the balance of this contract, then we shouldn't be giving them out.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) {
require(time >= lastUpdateTime, "Invalid end time for range");
if (totalLeveragedStakedSupply == 0) {
return 0;
}
uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable);
uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div(
totalLeveragedStakedSupply
);
// Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token.
// Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number
// of tokens that should have been disbursed in the elapsed time. The attacker would need to find
// a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1.
// See: https://twitter.com/Mudit__Gupta/status/1409463917290557440
if (additionalRewardsPerToken > rewardsSinceLastUpdate) {
return 0;
}
return additionalRewardsPerToken;
}
/// @notice Returns accumulated rewards per token up to the current block timestamp
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function rewardPerToken() public view returns (uint256) {
uint256 additionalRewardsPerToken = additionalRewardsPerTokenSinceLastUpdate(block.timestamp);
return accumulatedRewardsPerToken.add(additionalRewardsPerToken);
}
/// @notice Returns rewards earned by a given position token from its last checkpoint up to the
/// current block timestamp.
/// @param tokenId A staking position token ID
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return
leveredAmount.mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])).div(
stakingTokenMantissa()
);
}
/// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into
/// account vesting schedule.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) {
return positions[tokenId].rewards.claimable();
}
/// @notice Returns the rewards that will have vested for some position with the given params.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function totalVestedAt(
uint256 start,
uint256 end,
uint256 time,
uint256 grantedAmount
) external pure returns (uint256 rewards) {
return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount);
}
/// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second
function rewardRate() internal view returns (uint256) {
// The reward rate can be thought of as a piece-wise function:
//
// let intervalStart = (maxRateAtPercent * targetCapacity),
// intervalEnd = (minRateAtPercent * targetCapacity),
// x = totalStakedSupply
// in
// if x < intervalStart
// y = maxRate
// if x > intervalEnd
// y = minRate
// else
// y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart)
//
// See an example here:
// solhint-disable-next-line max-line-length
// https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D
//
// In that example:
// maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100
uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 x = totalStakedSupply;
// Subsequent computation would overflow
if (intervalEnd <= intervalStart) {
return 0;
}
if (x < intervalStart) {
return maxRate;
}
if (x > intervalEnd) {
return minRate;
}
return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart)));
}
function positionToLeveredAmount(StakedPosition storage position) internal view returns (uint256) {
return toLeveredAmount(position.amount, position.leverageMultiplier);
}
function toLeveredAmount(uint256 amount, uint256 leverageMultiplier) internal pure returns (uint256) {
return amount.mul(leverageMultiplier).div(MULTIPLIER_DECIMALS);
}
function stakingTokenMantissa() internal view returns (uint256) {
return uint256(10)**stakingToken().decimals();
}
/// @notice The amount of rewards currently being earned per token per second. This amount takes into
/// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not.
/// This function is intended for public consumption, to know the rate at which rewards are being
/// earned, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function currentEarnRatePerToken() public view returns (uint256) {
uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp;
uint256 elapsed = time.sub(lastUpdateTime);
return additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed);
}
/// @notice The amount of rewards currently being earned per second, for a given position. This function
/// is intended for public consumption, to know the rate at which rewards are being earned
/// for a given position, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return currentEarnRatePerToken().mul(leveredAmount).div(stakingTokenMantissa());
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an
/// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake`
/// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(0) {
_stakeWithLockup(msg.sender, msg.sender, amount, 0, MULTIPLIER_DECIMALS);
}
/// @notice Stake `stakingToken()` and lock your position for a period of time to boost your rewards.
/// When you call this function, you'll receive an an NFT representing your staked position.
/// You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens
/// respectively. Rewards vest over a schedule.
///
/// A locked position's rewards are boosted using a multiplier on the staked balance. For example,
/// if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens.
/// This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be
/// unstaked until after the position's lockedUntil timestamp.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
/// @param lockupPeriod The period over which to lock staked tokens
function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod)
external
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
_stakeWithLockup(msg.sender, msg.sender, amount, lockedUntil, leverageMultiplier);
}
/// @notice Deposit to SeniorPool and stake your shares in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) {
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockedUntil = 0;
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
}
function depositToSeniorPool(uint256 usdcAmount) internal returns (uint256 fiduAmount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
IERC20withDec usdc = config.getUSDC();
usdc.safeTransferFrom(msg.sender, address(this), usdcAmount);
ISeniorPool seniorPool = config.getSeniorPool();
usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount);
return seniorPool.deposit(usdcAmount);
}
/// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStake(
uint256 usdcAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStake(usdcAmount);
}
/// @notice Deposit to the `SeniorPool` and stake your shares with a lock-up in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
/// @param lockupPeriod The period over which to lock staked tokens
function depositAndStakeWithLockup(uint256 usdcAmount, LockupPeriod lockupPeriod)
public
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, leverageMultiplier);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, leverageMultiplier);
}
function lockupPeriodToDuration(LockupPeriod lockupPeriod) internal pure returns (uint256 lockDuration) {
if (lockupPeriod == LockupPeriod.SixMonths) {
return 365 days / 2;
} else if (lockupPeriod == LockupPeriod.TwelveMonths) {
return 365 days;
} else if (lockupPeriod == LockupPeriod.TwentyFourMonths) {
return 365 days * 2;
} else {
revert("unsupported LockupPeriod");
}
}
/// @notice Get the leverage multiplier used to boost rewards for a given lockup period.
/// See `stakeWithLockup`. The leverage multiplier is denominated in `MULTIPLIER_DECIMALS`.
function getLeverageMultiplier(LockupPeriod lockupPeriod) public view returns (uint256) {
uint256 leverageMultiplier = leverageMultipliers[lockupPeriod];
require(leverageMultiplier > 0, "unsupported LockupPeriod");
return leverageMultiplier;
}
/// @notice Identical to `depositAndStakeWithLockup`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param lockupPeriod The period over which to lock staked tokens
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStakeWithLockup(
uint256 usdcAmount,
LockupPeriod lockupPeriod,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStakeWithLockup(usdcAmount, lockupPeriod);
}
function _stakeWithLockup(
address staker,
address nftRecipient,
uint256 amount,
uint256 lockedUntil,
uint256 leverageMultiplier
) internal returns (uint256 tokenId) {
require(amount > 0, "Cannot stake 0");
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
// Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available
// We do this before setting the position, because we don't want `earned` to (incorrectly) account for
// position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original
// synthetix contract, where the modifier is called before any staking balance for that address is recorded
_updateReward(tokenId);
positions[tokenId] = StakedPosition({
amount: amount,
rewards: StakingRewardsVesting.Rewards({
totalUnvested: 0,
totalVested: 0,
totalPreviouslyVested: 0,
totalClaimed: 0,
startTime: block.timestamp,
endTime: block.timestamp.add(vestingLength)
}),
leverageMultiplier: leverageMultiplier,
lockedUntil: lockedUntil
});
_mint(nftRecipient, tokenId);
uint256 leveredAmount = positionToLeveredAmount(positions[tokenId]);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.add(leveredAmount);
totalStakedSupply = totalStakedSupply.add(amount);
// Staker is address(this) when using depositAndStake or other convenience functions
if (staker != address(this)) {
stakingToken().safeTransferFrom(staker, address(this), amount);
}
emit Staked(nftRecipient, tokenId, amount, lockedUntil, leverageMultiplier);
return tokenId;
}
/// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender.
/// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards.
/// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed.
/// @dev This function checkpoints rewards
/// @param tokenId A staking position token ID
/// @param amount Amount of `stakingToken()` to be unstaked from the position
function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) {
_unstake(tokenId, amount);
stakingToken().safeTransfer(msg.sender, amount);
}
function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) public nonReentrant whenNotPaused {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount)
internal
updateReward(tokenId)
returns (uint256 usdcAmountReceived, uint256 fiduUsed)
{
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
ISeniorPool seniorPool = config.getSeniorPool();
IFidu fidu = config.getFidu();
uint256 fiduBalanceBefore = fidu.balanceOf(address(this));
usdcAmountReceived = seniorPool.withdraw(usdcAmount);
fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this)));
_unstake(tokenId, fiduUsed);
config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived);
return (usdcAmountReceived, fiduUsed);
}
function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == usdcAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length);
for (uint256 i = 0; i < usdcAmounts.length; i++) {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
fiduAmounts[i] = fiduAmount;
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) public nonReentrant whenNotPaused {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount)
internal
updateReward(tokenId)
returns (uint256 usdcReceivedAmount)
{
usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount);
_unstake(tokenId, fiduAmount);
config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount);
return usdcReceivedAmount;
}
function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == fiduAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
for (uint256 i = 0; i < fiduAmounts.length; i++) {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function _unstake(uint256 tokenId, uint256 amount) internal {
require(ownerOf(tokenId) == msg.sender, "access denied");
require(amount > 0, "Cannot unstake 0");
StakedPosition storage position = positions[tokenId];
uint256 prevAmount = position.amount;
require(amount <= prevAmount, "cannot unstake more than staked balance");
require(block.timestamp >= position.lockedUntil, "staked funds are locked");
// By this point, leverageMultiplier should always be 1x due to the reset logic in updateReward.
// But we subtract leveredAmount from totalLeveragedStakedSupply anyway, since that is technically correct.
uint256 leveredAmount = toLeveredAmount(amount, position.leverageMultiplier);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(leveredAmount);
totalStakedSupply = totalStakedSupply.sub(amount);
position.amount = prevAmount.sub(amount);
// Slash unvested rewards
uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount);
position.rewards.slash(slashingPercentage);
emit Unstaked(msg.sender, tokenId, amount);
}
/// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward
/// multipler will be reset to 1x.
/// @dev This will also checkpoint their rewards up to the current time.
// solhint-disable-next-line no-empty-blocks
function kick(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {}
/// @notice Claim rewards for a given staked position
/// @param tokenId A staking position token ID
function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {
require(ownerOf(tokenId) == msg.sender, "access denied");
uint256 reward = claimableRewards(tokenId);
if (reward > 0) {
positions[tokenId].rewards.claim(reward);
rewardsToken().safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, tokenId, reward);
}
}
/// @notice Unstake the position's full amount and claim all rewards
/// @param tokenId A staking position token ID
function exit(uint256 tokenId) external {
unstake(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
function exitAndWithdraw(uint256 tokenId) external {
unstakeAndWithdrawInFidu(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/// @notice Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) {
rewardsToken().safeTransferFrom(msg.sender, address(this), rewards);
rewardsAvailable = rewardsAvailable.add(rewards);
emit RewardAdded(rewards);
}
function setRewardsParameters(
uint256 _targetCapacity,
uint256 _minRate,
uint256 _maxRate,
uint256 _minRateAtPercent,
uint256 _maxRateAtPercent
) public onlyAdmin updateReward(0) {
require(_maxRate >= _minRate, "maxRate must be >= then minRate");
require(_maxRateAtPercent <= _minRateAtPercent, "maxRateAtPercent must be <= minRateAtPercent");
targetCapacity = _targetCapacity;
minRate = _minRate;
maxRate = _maxRate;
minRateAtPercent = _minRateAtPercent;
maxRateAtPercent = _maxRateAtPercent;
emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent);
}
function setLeverageMultiplier(LockupPeriod lockupPeriod, uint256 leverageMultiplier)
public
onlyAdmin
updateReward(0)
{
leverageMultipliers[lockupPeriod] = leverageMultiplier;
emit LeverageMultiplierUpdated(msg.sender, lockupPeriod, leverageMultiplier);
}
function setVestingSchedule(uint256 _vestingLength) public onlyAdmin updateReward(0) {
vestingLength = _vestingLength;
emit VestingScheduleUpdated(msg.sender, vestingLength);
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ========== MODIFIERS ========== */
modifier updateReward(uint256 tokenId) {
_updateReward(tokenId);
_;
}
function _updateReward(uint256 tokenId) internal {
uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken;
accumulatedRewardsPerToken = rewardPerToken();
uint256 rewardsJustDistributed = totalLeveragedStakedSupply
.mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken))
.div(stakingTokenMantissa());
rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed);
lastUpdateTime = block.timestamp;
if (tokenId != 0) {
uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId);
StakedPosition storage position = positions[tokenId];
StakingRewardsVesting.Rewards storage rewards = position.rewards;
rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards);
rewards.checkpoint();
positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken;
// If position is unlocked, reset its leverageMultiplier back to 1x
uint256 lockedUntil = position.lockedUntil;
uint256 leverageMultiplier = position.leverageMultiplier;
uint256 amount = position.amount;
if (lockedUntil > 0 && block.timestamp >= lockedUntil && leverageMultiplier > MULTIPLIER_DECIMALS) {
uint256 prevLeveredAmount = toLeveredAmount(amount, leverageMultiplier);
uint256 newLeveredAmount = toLeveredAmount(amount, MULTIPLIER_DECIMALS);
position.leverageMultiplier = MULTIPLIER_DECIMALS;
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(prevLeveredAmount).add(newLeveredAmount);
}
}
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier);
event DepositedAndStaked(
address indexed user,
uint256 depositedAmount,
uint256 indexed tokenId,
uint256 amount,
uint256 lockedUntil,
uint256 multiplier
);
event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrewMultiple(
address indexed user,
uint256 usdcReceivedAmount,
uint256[] tokenIds,
uint256[] amounts
);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
}
| @notice The additional rewards earned per token, between the provided time and the last time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited by the amount of rewards that are available for distribution; if there aren't enough rewards in the balance of this contract, then we shouldn't be giving them out. @return Amount of rewards denominated in `rewardsToken().decimals()`. Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token. Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number of tokens that should have been disbursed in the elapsed time. The attacker would need to find a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1. See: https:twitter.com/Mudit__Gupta/status/1409463917290557440 | function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) {
require(time >= lastUpdateTime, "Invalid end time for range");
if (totalLeveragedStakedSupply == 0) {
return 0;
}
uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable);
uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div(
totalLeveragedStakedSupply
);
if (additionalRewardsPerToken > rewardsSinceLastUpdate) {
return 0;
}
return additionalRewardsPerToken;
}
| 1,799,947 | [
1,
1986,
3312,
283,
6397,
425,
1303,
329,
1534,
1147,
16,
3086,
326,
2112,
813,
471,
326,
1142,
282,
813,
283,
6397,
4591,
9776,
329,
16,
864,
326,
2807,
671,
310,
1375,
266,
2913,
4727,
1435,
8338,
1220,
3844,
353,
13594,
282,
635,
326,
3844,
434,
283,
6397,
716,
854,
2319,
364,
7006,
31,
309,
1915,
11526,
1404,
7304,
282,
283,
6397,
316,
326,
11013,
434,
333,
6835,
16,
1508,
732,
12044,
1404,
506,
21057,
2182,
596,
18,
327,
16811,
434,
283,
6397,
10716,
7458,
316,
1375,
266,
6397,
1345,
7675,
31734,
1435,
8338,
19412,
1534,
2476,
16,
14853,
17,
81,
474,
10766,
1625,
2078,
1682,
502,
11349,
510,
9477,
3088,
1283,
353,
279,
8330,
434,
279,
1147,
18,
7897,
518,
1807,
1399,
487,
326,
15030,
16,
333,
3377,
1221,
3312,
17631,
1060,
2173,
1345,
10974,
2353,
326,
2078,
1300,
434,
2430,
716,
1410,
1240,
2118,
1015,
70,
295,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
225,
445,
3312,
17631,
14727,
2173,
1345,
9673,
3024,
1891,
12,
11890,
5034,
813,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
12,
957,
1545,
1142,
1891,
950,
16,
315,
1941,
679,
813,
364,
1048,
8863,
203,
203,
565,
309,
261,
4963,
1682,
502,
11349,
510,
9477,
3088,
1283,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
565,
2254,
5034,
283,
6397,
9673,
3024,
1891,
273,
2361,
18,
1154,
12,
957,
18,
1717,
12,
2722,
1891,
950,
2934,
16411,
12,
266,
2913,
4727,
1435,
3631,
283,
6397,
5268,
1769,
203,
565,
2254,
5034,
3312,
17631,
14727,
2173,
1345,
273,
283,
6397,
9673,
3024,
1891,
18,
16411,
12,
334,
6159,
1345,
49,
970,
21269,
1435,
2934,
2892,
12,
203,
1377,
2078,
1682,
502,
11349,
510,
9477,
3088,
1283,
203,
565,
11272,
203,
565,
309,
261,
13996,
17631,
14727,
2173,
1345,
405,
283,
6397,
9673,
3024,
1891,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
565,
327,
3312,
17631,
14727,
2173,
1345,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x950b1756c44c95a4469e915484b6AEdFA134F434/sources/project_/contracts/Gestor.sol | Función para minar o quemar los tokens de TODOS dependiendo de si _valor vale 0 o no | function modificarValor(uint256 _nuevoValor, uint8 _valor) public {
valor = _nuevoValor;
if(_valor == 0)
{
emit ValorModificado(valor);
Traductores(traductoresContract).modificarValorTraductores(valor);
}
else {
emit ValorModificado(valor);
Traductores(traductoresContract).BurnTraductores(valor);
}
}
| 9,538,154 | [
1,
2622,
77,
132,
116,
82,
12602,
1131,
297,
320,
6597,
3684,
22148,
2430,
443,
2660,
55,
2447,
77,
409,
83,
443,
7533,
389,
1125,
280,
1244,
73,
374,
320,
1158,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
681,
1507,
297,
3053,
280,
12,
11890,
5034,
389,
82,
344,
12307,
3053,
280,
16,
2254,
28,
389,
1125,
280,
13,
1071,
225,
288,
203,
3639,
23325,
273,
389,
82,
344,
12307,
3053,
280,
31,
203,
3639,
309,
24899,
1125,
280,
422,
374,
13,
203,
3639,
288,
203,
3639,
3626,
12747,
280,
1739,
1507,
6821,
12,
1125,
280,
1769,
203,
203,
3639,
2197,
1828,
3485,
12,
313,
361,
853,
3485,
8924,
2934,
1711,
1507,
297,
3053,
280,
1609,
1828,
3485,
12,
1125,
280,
1769,
203,
3639,
289,
203,
3639,
469,
288,
203,
203,
3639,
3626,
12747,
280,
1739,
1507,
6821,
12,
1125,
280,
1769,
203,
203,
3639,
2197,
1828,
3485,
12,
313,
361,
853,
3485,
8924,
2934,
38,
321,
1609,
1828,
3485,
12,
1125,
280,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import {InitializedProxy} from "./InitializedProxy.sol";
import {PartyBid} from "./PartyBid.sol";
/**
* @title PartyBid Factory
* @author Anna Carroll
*
* WARNING: A malicious MarketWrapper contract could be used to steal user funds;
* A poorly implemented MarketWrapper contract could permanently lose access to the NFT.
* When deploying a PartyBid, exercise extreme caution.
* Only use MarketWrapper contracts that have been audited and tested.
*/
contract PartyBidFactory {
//======== Events ========
event PartyBidDeployed(
address partyBidProxy,
address creator,
address nftContract,
uint256 tokenId,
address marketWrapper,
uint256 auctionId,
address splitRecipient,
uint256 splitBasisPoints,
string name,
string symbol
);
//======== Immutable storage =========
address public immutable logic;
address public immutable partyDAOMultisig;
address public immutable tokenVaultFactory;
address public immutable weth;
//======== Mutable storage =========
// PartyBid proxy => block number deployed at
mapping(address => uint256) public deployedAt;
//======== Constructor =========
constructor(
address _partyDAOMultisig,
address _tokenVaultFactory,
address _weth,
address _logicMarketWrapper,
address _logicNftContract,
uint256 _logicTokenId,
uint256 _logicAuctionId
) {
partyDAOMultisig = _partyDAOMultisig;
tokenVaultFactory = _tokenVaultFactory;
weth = _weth;
// deploy logic contract
PartyBid _logicContract = new PartyBid(_partyDAOMultisig, _tokenVaultFactory, _weth);
// initialize logic contract
_logicContract.initialize(
_logicMarketWrapper,
_logicNftContract,
_logicTokenId,
_logicAuctionId,
address(0),
0,
"PartyBid",
"BID"
);
// store logic contract address
logic = address(_logicContract);
}
//======== Deploy function =========
function startParty(
address _marketWrapper,
address _nftContract,
uint256 _tokenId,
uint256 _auctionId,
address _splitRecipient,
uint256 _splitBasisPoints,
string memory _name,
string memory _symbol
) external returns (address partyBidProxy) {
bytes memory _initializationCalldata =
abi.encodeWithSignature(
"initialize(address,address,uint256,uint256,address,uint256,string,string)",
_marketWrapper,
_nftContract,
_tokenId,
_auctionId,
_splitRecipient,
_splitBasisPoints,
_name,
_symbol
);
partyBidProxy = address(
new InitializedProxy(
logic,
_initializationCalldata
)
);
deployedAt[partyBidProxy] = block.number;
emit PartyBidDeployed(
partyBidProxy,
msg.sender,
_nftContract,
_tokenId,
_marketWrapper,
_auctionId,
_splitRecipient,
_splitBasisPoints,
_name,
_symbol
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/**
* @title InitializedProxy
* @author Anna Carroll
*/
contract InitializedProxy {
// address of logic contract
address public immutable logic;
// ======== Constructor =========
constructor(
address _logic,
bytes memory _initializationCalldata
) {
logic = _logic;
// Delegatecall into the logic contract, supplying initialization calldata
(bool _ok, bytes memory returnData) =
_logic.delegatecall(_initializationCalldata);
// Revert if delegatecall to implementation reverts
require(_ok, string(returnData));
}
// ======== Fallback =========
fallback() external payable {
address _impl = logic;
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
// ======== Receive =========
receive() external payable {} // solhint-disable-line no-empty-blocks
}
/*
___ ___ ___ ___ ___ ___ ___
/\ \ /\ \ /\ \ /\ \ |\__\ /\ \ ___ /\ \
/::\ \ /::\ \ /::\ \ \:\ \ |:| | /::\ \ /\ \ /::\ \
/:/\:\ \ /:/\:\ \ /:/\:\ \ \:\ \ |:| | /:/\:\ \ \:\ \ /:/\:\ \
/::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\ \ |:|__|__ /::\~\:\__\ /::\__\ /:/ \:\__\
/:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\__\ /::::\__\ /:/\:\ \:|__| __/:/\/__/ /:/__/ \:|__|
\/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / /:/ \/__/ /:/~~/~ \:\~\:\/:/ / /\/:/ / \:\ \ /:/ /
\::/ / \::/ / |:|::/ / /:/ / /:/ / \:\ \::/ / \::/__/ \:\ /:/ /
\/__/ /:/ / |:|\/__/ \/__/ \/__/ \:\/:/ / \:\__\ \:\/:/ /
/:/ / |:| | \::/__/ \/__/ \::/__/
\/__/ \|__| ~~ ~~
PartyBid v1
Anna Carroll for PartyDAO
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
// ============ External Imports: Inherited Contracts ============
// NOTE: we inherit from OpenZeppelin upgradeable contracts
// because of the proxy structure used for cheaper deploys
// (the proxies are NOT actually upgradeable)
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
ERC721HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
// ============ External Imports: External Contracts & Contract Interfaces ============
import {
IERC721VaultFactory
} from "./external/interfaces/IERC721VaultFactory.sol";
import {ITokenVault} from "./external/interfaces/ITokenVault.sol";
import {
IERC721Metadata
} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {IWETH} from "./external/interfaces/IWETH.sol";
// ============ Internal Imports ============
import {IMarketWrapper} from "./market-wrapper/IMarketWrapper.sol";
contract PartyBid is ReentrancyGuardUpgradeable, ERC721HolderUpgradeable {
// ============ Enums ============
// State Transitions:
// (1) AUCTION_ACTIVE on deploy
// (2) AUCTION_WON or AUCTION_LOST on finalize()
enum PartyStatus {AUCTION_ACTIVE, AUCTION_WON, AUCTION_LOST}
// ============ Structs ============
struct Contribution {
uint256 amount;
uint256 previousTotalContributedToParty;
}
// ============ Internal Constants ============
// PartyBid version 2
uint16 public constant VERSION = 2;
// tokens are minted at a rate of 1 ETH : 1000 tokens
uint16 internal constant TOKEN_SCALE = 1000;
// PartyDAO receives an ETH fee equal to 2.5% of the winning bid
uint16 internal constant ETH_FEE_BASIS_POINTS = 250;
// PartyDAO receives a token fee equal to 2.5% of the total token supply
uint16 internal constant TOKEN_FEE_BASIS_POINTS = 250;
// token is relisted on Fractional with an
// initial reserve price equal to 2x the winning bid
uint8 internal constant RESALE_MULTIPLIER = 2;
// ============ Immutables ============
address public immutable partyDAOMultisig;
IERC721VaultFactory public immutable tokenVaultFactory;
IWETH public immutable weth;
// ============ Public Not-Mutated Storage ============
// market wrapper contract exposing interface for
// market auctioning the NFT
IMarketWrapper public marketWrapper;
// NFT contract
IERC721Metadata public nftContract;
// Fractionalized NFT vault responsible for post-auction value capture
ITokenVault public tokenVault;
// ID of auction within market contract
uint256 public auctionId;
// ID of token within NFT contract
uint256 public tokenId;
// the address that will receive a portion of the tokens
// if the PartyBid wins the auction
address public splitRecipient;
// percent of the total token supply
// taken by the splitRecipient
uint256 public splitBasisPoints;
// ERC-20 name and symbol for fractional tokens
string public name;
string public symbol;
// ============ Public Mutable Storage ============
// state of the contract
PartyStatus public partyStatus;
// total ETH deposited by all contributors
uint256 public totalContributedToParty;
// the highest bid submitted by PartyBid
uint256 public highestBid;
// the total spent by PartyBid on the auction;
// 0 if the NFT is lost; highest bid + 2.5% PartyDAO fee if NFT is won
uint256 public totalSpent;
// contributor => array of Contributions
mapping(address => Contribution[]) public contributions;
// contributor => total amount contributed
mapping(address => uint256) public totalContributed;
// contributor => true if contribution has been claimed
mapping(address => bool) public claimed;
// ============ Events ============
event Contributed(
address indexed contributor,
uint256 amount,
uint256 previousTotalContributedToParty,
uint256 totalFromContributor
);
event Bid(uint256 amount);
event Finalized(PartyStatus result, uint256 totalSpent, uint256 fee, uint256 totalContributed);
event Claimed(
address indexed contributor,
uint256 totalContributed,
uint256 excessContribution,
uint256 tokenAmount
);
// ======== Modifiers =========
modifier onlyPartyDAO() {
require(
msg.sender == partyDAOMultisig,
"PartyBid:: only PartyDAO multisig"
);
_;
}
// ======== Constructor =========
constructor(
address _partyDAOMultisig,
address _tokenVaultFactory,
address _weth
) {
partyDAOMultisig = _partyDAOMultisig;
tokenVaultFactory = IERC721VaultFactory(_tokenVaultFactory);
weth = IWETH(_weth);
}
// ======== Initializer =========
function initialize(
address _marketWrapper,
address _nftContract,
uint256 _tokenId,
uint256 _auctionId,
address _splitRecipient,
uint256 _splitBasisPoints,
string memory _name,
string memory _symbol
) external initializer {
// initialize ReentrancyGuard and ERC721Holder
__ReentrancyGuard_init();
__ERC721Holder_init();
// set storage variables
marketWrapper = IMarketWrapper(_marketWrapper);
nftContract = IERC721Metadata(_nftContract);
tokenId = _tokenId;
auctionId = _auctionId;
name = _name;
symbol = _symbol;
// validate that party split won't retain the total token supply
uint256 _remainingBasisPoints = 10000 - TOKEN_FEE_BASIS_POINTS;
require(_splitBasisPoints < _remainingBasisPoints, "PartyBid::initialize: basis points can't take 100%");
// validate that a portion of the token supply is not being burned
if (_splitRecipient == address(0)) {
require(_splitBasisPoints == 0, "PartyBid::initialize: can't send tokens to burn addr");
}
splitBasisPoints = _splitBasisPoints;
splitRecipient = _splitRecipient;
// validate token exists
require(_getOwner() != address(0), "PartyBid::initialize: NFT getOwner failed");
// validate auction exists
require(
marketWrapper.auctionIdMatchesToken(
_auctionId,
_nftContract,
_tokenId
),
"PartyBid::initialize: auctionId doesn't match token"
);
}
// ======== External: Contribute =========
/**
* @notice Contribute to the PartyBid's treasury
* while the auction is still open
* @dev Emits a Contributed event upon success; callable by anyone
*/
function contribute() external payable nonReentrant {
require(
partyStatus == PartyStatus.AUCTION_ACTIVE,
"PartyBid::contribute: auction not active"
);
address _contributor = msg.sender;
uint256 _amount = msg.value;
require(_amount > 0, "PartyBid::contribute: must contribute more than 0");
// get the current contract balance
uint256 _previousTotalContributedToParty = totalContributedToParty;
// add contribution to contributor's array of contributions
Contribution memory _contribution =
Contribution({
amount: _amount,
previousTotalContributedToParty: _previousTotalContributedToParty
});
contributions[_contributor].push(_contribution);
// add to contributor's total contribution
totalContributed[_contributor] =
totalContributed[_contributor] +
_amount;
// add to party's total contribution & emit event
totalContributedToParty = totalContributedToParty + _amount;
emit Contributed(
_contributor,
_amount,
_previousTotalContributedToParty,
totalContributed[_contributor]
);
}
// ======== External: Bid =========
/**
* @notice Submit a bid to the Market
* @dev Reverts if insufficient funds to place the bid and pay PartyDAO fees,
* or if any external auction checks fail (including if PartyBid is current high bidder)
* Emits a Bid event upon success.
* Callable by any contributor
*/
function bid() external nonReentrant {
require(
partyStatus == PartyStatus.AUCTION_ACTIVE,
"PartyBid::bid: auction not active"
);
require(
totalContributed[msg.sender] > 0,
"PartyBid::bid: only contributors can bid"
);
require(
address(this) !=
marketWrapper.getCurrentHighestBidder(
auctionId
),
"PartyBid::bid: already highest bidder"
);
require(
!marketWrapper.isFinalized(auctionId),
"PartyBid::bid: auction already finalized"
);
// get the minimum next bid for the auction
uint256 _bid = marketWrapper.getMinimumBid(auctionId);
// ensure there is enough ETH to place the bid including PartyDAO fee
require(
_bid <= getMaximumBid(),
"PartyBid::bid: insufficient funds to bid"
);
// submit bid to Auction contract using delegatecall
(bool success, bytes memory returnData) =
address(marketWrapper).delegatecall(
abi.encodeWithSignature("bid(uint256,uint256)", auctionId, _bid)
);
require(
success,
string(
abi.encodePacked(
"PartyBid::bid: place bid failed: ",
returnData
)
)
);
// update highest bid submitted & emit success event
highestBid = _bid;
emit Bid(_bid);
}
// ======== External: Finalize =========
/**
* @notice Finalize the state of the auction
* @dev Emits a Finalized event upon success; callable by anyone
*/
function finalize() external nonReentrant {
require(
partyStatus == PartyStatus.AUCTION_ACTIVE,
"PartyBid::finalize: auction not active"
);
// finalize auction if it hasn't already been done
if (!marketWrapper.isFinalized(auctionId)) {
marketWrapper.finalize(auctionId);
}
// after the auction has been finalized,
// if the NFT is owned by the PartyBid, then the PartyBid won the auction
address _owner = _getOwner();
partyStatus = _owner == address(this) ? PartyStatus.AUCTION_WON : PartyStatus.AUCTION_LOST;
uint256 _ethFee;
// if the auction was won,
if (partyStatus == PartyStatus.AUCTION_WON) {
// calculate PartyDAO fee & record total spent
_ethFee = _getEthFee(highestBid);
totalSpent = highestBid + _ethFee;
// transfer ETH fee to PartyDAO
_transferETHOrWETH(partyDAOMultisig, _ethFee);
// deploy fractionalized NFT vault
// and mint fractional ERC-20 tokens
_fractionalizeNFT();
}
// set the contract status & emit result
emit Finalized(partyStatus, totalSpent, _ethFee, totalContributedToParty);
}
// ======== External: Claim =========
/**
* @notice Claim the tokens and excess ETH owed
* to a single contributor after the auction has ended
* @dev Emits a Claimed event upon success
* callable by anyone (doesn't have to be the contributor)
* @param _contributor the address of the contributor
*/
function claim(address _contributor) external nonReentrant {
// ensure auction has finalized
require(
partyStatus != PartyStatus.AUCTION_ACTIVE,
"PartyBid::claim: auction not finalized"
);
// ensure contributor submitted some ETH
require(
totalContributed[_contributor] != 0,
"PartyBid::claim: not a contributor"
);
// ensure the contributor hasn't already claimed
require(
!claimed[_contributor],
"PartyBid::claim: contribution already claimed"
);
// mark the contribution as claimed
claimed[_contributor] = true;
// calculate the amount of fractional NFT tokens owed to the user
// based on how much ETH they contributed towards the auction,
// and the amount of excess ETH owed to the user
(uint256 _tokenAmount, uint256 _ethAmount) =
getClaimAmounts(_contributor);
// transfer tokens to contributor for their portion of ETH used
_transferTokens(_contributor, _tokenAmount);
// if there is excess ETH, send it back to the contributor
_transferETHOrWETH(_contributor, _ethAmount);
emit Claimed(
_contributor,
totalContributed[_contributor],
_ethAmount,
_tokenAmount
);
}
// ======== External: Emergency Escape Hatches (PartyDAO Multisig Only) =========
/**
* @notice Escape hatch: in case of emergency,
* PartyDAO can use emergencyWithdrawEth to withdraw
* ETH stuck in the contract
*/
function emergencyWithdrawEth(uint256 _value)
external
onlyPartyDAO
{
_transferETHOrWETH(partyDAOMultisig, _value);
}
/**
* @notice Escape hatch: in case of emergency,
* PartyDAO can use emergencyCall to call an external contract
* (e.g. to withdraw a stuck NFT or stuck ERC-20s)
*/
function emergencyCall(address _contract, bytes memory _calldata)
external
onlyPartyDAO
returns (bool _success, bytes memory _returnData)
{
(_success, _returnData) = _contract.call(_calldata);
require(_success, string(_returnData));
}
/**
* @notice Escape hatch: in case of emergency,
* PartyDAO can force the PartyBid to finalize with status LOST
* (e.g. if finalize is not callable)
*/
function emergencyForceLost()
external
onlyPartyDAO
{
// set partyStatus to LOST
partyStatus = PartyStatus.AUCTION_LOST;
// emit Finalized event
emit Finalized(partyStatus, 0, 0, totalContributedToParty);
}
// ======== Public: Utility Calculations =========
/**
* @notice Convert ETH value to equivalent token amount
*/
function valueToTokens(uint256 _value)
public
pure
returns (uint256 _tokens)
{
_tokens = _value * TOKEN_SCALE;
}
/**
* @notice The maximum bid that can be submitted
* while paying the ETH fee to PartyDAO
* @return _maxBid the maximum bid
*/
function getMaximumBid() public view returns (uint256 _maxBid) {
_maxBid = (totalContributedToParty * 10000) / (10000 + ETH_FEE_BASIS_POINTS);
}
/**
* @notice Calculate the amount of fractional NFT tokens owed to the contributor
* based on how much ETH they contributed towards the auction,
* and the amount of excess ETH owed to the contributor
* based on how much ETH they contributed *not* used towards the auction
* @param _contributor the address of the contributor
* @return _tokenAmount the amount of fractional NFT tokens owed to the contributor
* @return _ethAmount the amount of excess ETH owed to the contributor
*/
function getClaimAmounts(address _contributor)
public
view
returns (uint256 _tokenAmount, uint256 _ethAmount)
{
require(partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::getClaimAmounts: party still active; amounts undetermined");
uint256 _totalContributed = totalContributed[_contributor];
if (partyStatus == PartyStatus.AUCTION_WON) {
// calculate the amount of this contributor's ETH
// that was used for the winning bid
uint256 _totalUsedForBid = totalEthUsedForBid(_contributor);
if (_totalUsedForBid > 0) {
_tokenAmount = valueToTokens(_totalUsedForBid);
}
// the rest of the contributor's ETH should be returned
_ethAmount = _totalContributed - _totalUsedForBid;
} else {
// if the auction was lost, no ETH was spent;
// all of the contributor's ETH should be returned
_ethAmount = _totalContributed;
}
}
/**
* @notice Calculate the total amount of a contributor's funds
* that were used towards the winning auction bid
* @dev always returns 0 until the auction has been finalized
* @param _contributor the address of the contributor
* @return _total the sum of the contributor's funds that were
* used towards the winning auction bid
*/
function totalEthUsedForBid(address _contributor)
public
view
returns (uint256 _total)
{
require(partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::totalEthUsedForBid: party still active; amounts undetermined");
// load total amount spent once from storage
uint256 _totalSpent = totalSpent;
// get all of the contributor's contributions
Contribution[] memory _contributions = contributions[_contributor];
for (uint256 i = 0; i < _contributions.length; i++) {
// calculate how much was used from this individual contribution
uint256 _amount = _ethUsedForBid(_totalSpent, _contributions[i]);
// if we reach a contribution that was not used,
// no subsequent contributions will have been used either,
// so we can stop calculating to save some gas
if (_amount == 0) break;
_total = _total + _amount;
}
}
// ============ Internal: Bid ============
/**
* @notice Calculate ETH fee for PartyDAO
* NOTE: Remove this fee causes a critical vulnerability
* allowing anyone to exploit a PartyBid via price manipulation.
* See Security Review in README for more info.
* @return _fee the portion of _amount represented by scaling to ETH_FEE_BASIS_POINTS
*/
function _getEthFee(uint256 _winningBid) internal pure returns (uint256 _fee) {
_fee = (_winningBid * ETH_FEE_BASIS_POINTS) / 10000;
}
/**
* @notice Calculate token amount for specified token recipient
* @return _totalSupply the total token supply
* @return _partyDAOAmount the amount of tokens for partyDAO fee,
* which is equivalent to TOKEN_FEE_BASIS_POINTS of total supply
* @return _splitRecipientAmount the amount of tokens for the token recipient,
* which is equivalent to splitBasisPoints of total supply
*/
function _getTokenInflationAmounts(uint256 _winningBid)
internal
view
returns (uint256 _totalSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount)
{
// the token supply will be inflated to provide a portion of the
// total supply for PartyDAO, and a portion for the splitRecipient
uint256 inflationBasisPoints = TOKEN_FEE_BASIS_POINTS + splitBasisPoints;
_totalSupply = valueToTokens((_winningBid * 10000) / (10000 - inflationBasisPoints));
// PartyDAO receives TOKEN_FEE_BASIS_POINTS of the total supply
_partyDAOAmount = (_totalSupply * TOKEN_FEE_BASIS_POINTS) / 10000;
// splitRecipient receives splitBasisPoints of the total supply
_splitRecipientAmount = (_totalSupply * splitBasisPoints) / 10000;
}
// ============ Internal: Finalize ============
/**
* @notice Query the NFT contract to get the token owner
* @dev nftContract must implement the ERC-721 token standard exactly:
* function ownerOf(uint256 _tokenId) external view returns (address);
* See https://eips.ethereum.org/EIPS/eip-721
* @dev Returns address(0) if NFT token or NFT contract
* no longer exists (token burned or contract self-destructed)
* @return _owner the owner of the NFT
*/
function _getOwner() internal view returns (address _owner) {
(bool success, bytes memory returnData) =
address(nftContract).staticcall(
abi.encodeWithSignature(
"ownerOf(uint256)",
tokenId
)
);
if (success && returnData.length > 0) {
_owner = abi.decode(returnData, (address));
}
}
/**
* @notice Upon winning the auction, transfer the NFT
* to fractional.art vault & mint fractional ERC-20 tokens
*/
function _fractionalizeNFT() internal {
// approve fractionalized NFT Factory to withdraw NFT
nftContract.approve(address(tokenVaultFactory), tokenId);
// PartyBid "votes" for a reserve price on Fractional
// equal to 2x the winning bid
uint256 _listPrice = RESALE_MULTIPLIER * highestBid;
// users receive tokens at a rate of 1:TOKEN_SCALE for each ETH they contributed that was ultimately spent
// partyDAO receives a percentage of the total token supply equivalent to TOKEN_FEE_BASIS_POINTS
// splitRecipient receives a percentage of the total token supply equivalent to splitBasisPoints
(uint256 _tokenSupply, uint256 _partyDAOAmount, uint256 _splitRecipientAmount) = _getTokenInflationAmounts(totalSpent);
// deploy fractionalized NFT vault
uint256 vaultNumber =
tokenVaultFactory.mint(
name,
symbol,
address(nftContract),
tokenId,
_tokenSupply,
_listPrice,
0
);
// store token vault address to storage
tokenVault = ITokenVault(tokenVaultFactory.vaults(vaultNumber));
// transfer curator to null address (burn the curator role)
tokenVault.updateCurator(address(0));
// transfer tokens to PartyDAO multisig
_transferTokens(partyDAOMultisig, _partyDAOAmount);
// transfer tokens to token recipient
if (splitRecipient != address(0)) {
_transferTokens(splitRecipient, _splitRecipientAmount);
}
}
// ============ Internal: Claim ============
/**
* @notice Calculate the amount that was used towards
* the winning auction bid from a single Contribution
* @param _contribution the Contribution struct
* @return the amount of funds from this contribution
* that were used towards the winning auction bid
*/
function _ethUsedForBid(uint256 _totalSpent, Contribution memory _contribution)
internal
view
returns (uint256)
{
if (
_contribution.previousTotalContributedToParty +
_contribution.amount <=
_totalSpent
) {
// contribution was fully used
return _contribution.amount;
} else if (
_contribution.previousTotalContributedToParty < _totalSpent
) {
// contribution was partially used
return _totalSpent - _contribution.previousTotalContributedToParty;
}
// contribution was not used
return 0;
}
// ============ Internal: TransferTokens ============
/**
* @notice Transfer tokens to a recipient
* @param _to recipient of tokens
* @param _value amount of tokens
*/
function _transferTokens(address _to, uint256 _value) internal {
// skip if attempting to send 0 tokens
if (_value == 0) {
return;
}
// guard against rounding errors;
// if token amount to send is greater than contract balance,
// send full contract balance
uint256 _partyBidBalance = tokenVault.balanceOf(address(this));
if (_value > _partyBidBalance) {
_value = _partyBidBalance;
}
tokenVault.transfer(_to, _value);
}
// ============ Internal: TransferEthOrWeth ============
/**
* @notice Attempt to transfer ETH to a recipient;
* if transferring ETH fails, transfer WETH insteads
* @param _to recipient of ETH or WETH
* @param _value amount of ETH or WETH
*/
function _transferETHOrWETH(address _to, uint256 _value) internal {
// skip if attempting to send 0 ETH
if (_value == 0) {
return;
}
// guard against rounding errors;
// if ETH amount to send is greater than contract balance,
// send full contract balance
if (_value > address(this).balance) {
_value = address(this).balance;
}
// Try to transfer ETH to the given recipient.
if (!_attemptETHTransfer(_to, _value)) {
// If the transfer fails, wrap and send as WETH
weth.deposit{value: _value}();
weth.transfer(_to, _value);
// At this point, the recipient can unwrap WETH.
}
}
/**
* @notice Attempt to transfer ETH to a recipient
* @dev Sending ETH is not guaranteed to succeed
* this method will return false if it fails.
* We will limit the gas used in transfers, and handle failure cases.
* @param _to recipient of ETH
* @param _value amount of ETH
*/
function _attemptETHTransfer(address _to, uint256 _value)
internal
returns (bool)
{
// Here increase the gas limit a reasonable amount above the default, and try
// to send ETH to the recipient.
// NOTE: This might allow the recipient to attempt a limited reentrancy attack.
(bool success, ) = _to.call{value: _value, gas: 30000}("");
return success;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable {
function __ERC721Holder_init() internal initializer {
__ERC721Holder_init_unchained();
}
function __ERC721Holder_init_unchained() internal initializer {
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
uint256[50] private __gap;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
interface IERC721VaultFactory {
/// @notice the mapping of vault number to vault address
function vaults(uint256) external returns (address);
/// @notice the function to mint a new vault
/// @param _name the desired name of the vault
/// @param _symbol the desired sumbol of the vault
/// @param _token the ERC721 token address fo the NFT
/// @param _id the uint256 ID of the token
/// @param _listPrice the initial price of the NFT
/// @return the ID of the vault
function mint(string memory _name, string memory _symbol, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee) external returns(uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
interface ITokenVault {
/// @notice allow curator to update the curator address
/// @param _curator the new curator
function updateCurator(address _curator) external;
/**
* @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) external returns (bool);
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256);
}
// 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.5;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/**
* @title IMarketWrapper
* @author Anna Carroll
* @notice IMarketWrapper provides a common interface for
* interacting with NFT auction markets.
* Contracts can abstract their interactions with
* different NFT markets using IMarketWrapper.
* NFT markets can become compatible with any contract
* using IMarketWrapper by deploying a MarketWrapper contract
* that implements this interface using the logic of their Market.
*
* WARNING: MarketWrapper contracts should NEVER write to storage!
* When implementing a MarketWrapper, exercise caution; a poorly implemented
* MarketWrapper contract could permanently lose access to the NFT or user funds.
*/
interface IMarketWrapper {
/**
* @notice Given the auctionId, nftContract, and tokenId, check that:
* 1. the auction ID matches the token
* referred to by tokenId + nftContract
* 2. the auctionId refers to an *ACTIVE* auction
* (e.g. an auction that will accept bids)
* within this market contract
* 3. any additional validation to ensure that
* a PartyBid can bid on this auction
* (ex: if the market allows arbitrary bidding currencies,
* check that the auction currency is ETH)
* Note: This function probably should have been named "isValidAuction"
* @dev Called in PartyBid.sol in `initialize` at line 174
* @return TRUE if the auction is valid
*/
function auctionIdMatchesToken(
uint256 auctionId,
address nftContract,
uint256 tokenId
) external view returns (bool);
/**
* @notice Calculate the minimum next bid for this auction.
* PartyBid contracts always submit the minimum possible
* bid that will be accepted by the Market contract.
* usually, this is either the reserve price (if there are no bids)
* or a certain percentage increase above the current highest bid
* @dev Called in PartyBid.sol in `bid` at line 251
* @return minimum bid amount
*/
function getMinimumBid(uint256 auctionId) external view returns (uint256);
/**
* @notice Query the current highest bidder for this auction
* It is assumed that there is always 1 winning highest bidder for an auction
* This is used to ensure that PartyBid cannot outbid itself if it is already winning
* @dev Called in PartyBid.sol in `bid` at line 241
* @return highest bidder
*/
function getCurrentHighestBidder(uint256 auctionId)
external
view
returns (address);
/**
* @notice Submit bid to Market contract
* @dev Called in PartyBid.sol in `bid` at line 259
*/
function bid(uint256 auctionId, uint256 bidAmount) external;
/**
* @notice Determine whether the auction has been finalized
* Used to check if it is still possible to bid
* And to determine whether the PartyBid should finalize the auction
* @dev Called in PartyBid.sol in `bid` at line 247
* @dev and in `finalize` at line 288
* @return TRUE if the auction has been finalized
*/
function isFinalized(uint256 auctionId) external view returns (bool);
/**
* @notice Finalize the results of the auction
* on the Market contract
* It is assumed that this operation is performed once for each auction,
* that after it is done the auction is over and the NFT has been
* transferred to the auction winner.
* @dev Called in PartyBid.sol in `finalize` at line 289
*/
function finalize(uint256 auctionId) external;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// 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 IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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;
/**
* @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);
}
| * @title IMarketWrapper @author Anna Carroll @notice IMarketWrapper provides a common interface for interacting with NFT auction markets. Contracts can abstract their interactions with different NFT markets using IMarketWrapper. NFT markets can become compatible with any contract using IMarketWrapper by deploying a MarketWrapper contract that implements this interface using the logic of their Market. WARNING: MarketWrapper contracts should NEVER write to storage! When implementing a MarketWrapper, exercise caution; a poorly implemented MarketWrapper contract could permanently lose access to the NFT or user funds./ | interface IMarketWrapper {
function auctionIdMatchesToken(
uint256 auctionId,
address nftContract,
uint256 tokenId
) external view returns (bool);
function getMinimumBid(uint256 auctionId) external view returns (uint256);
function getCurrentHighestBidder(uint256 auctionId)
external
view
returns (address);
function bid(uint256 auctionId, uint256 bidAmount) external;
function isFinalized(uint256 auctionId) external view returns (bool);
function finalize(uint256 auctionId) external;
pragma solidity 0.8.5;
}
| 102,773 | [
1,
3445,
1313,
278,
3611,
225,
1922,
6582,
23672,
2693,
225,
467,
3882,
278,
3611,
8121,
279,
2975,
1560,
364,
16592,
310,
598,
423,
4464,
279,
4062,
2267,
2413,
18,
30131,
848,
8770,
3675,
23877,
598,
3775,
423,
4464,
2267,
2413,
1450,
467,
3882,
278,
3611,
18,
423,
4464,
2267,
2413,
848,
12561,
7318,
598,
1281,
6835,
1450,
467,
3882,
278,
3611,
635,
7286,
310,
279,
6622,
278,
3611,
6835,
716,
4792,
333,
1560,
1450,
326,
4058,
434,
3675,
6622,
278,
18,
9744,
30,
6622,
278,
3611,
20092,
1410,
12901,
2204,
1045,
358,
2502,
5,
5203,
19981,
279,
6622,
278,
3611,
16,
24165,
3474,
1421,
31,
279,
8275,
280,
715,
8249,
6622,
278,
3611,
6835,
3377,
16866,
715,
29612,
2006,
358,
326,
423,
4464,
578,
729,
284,
19156,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
3882,
278,
3611,
288,
203,
565,
445,
279,
4062,
548,
6869,
1345,
12,
203,
3639,
2254,
5034,
279,
4062,
548,
16,
203,
3639,
1758,
290,
1222,
8924,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
30665,
17763,
12,
11890,
5034,
279,
4062,
548,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
5175,
8573,
395,
17763,
765,
12,
11890,
5034,
279,
4062,
548,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
1769,
203,
203,
565,
445,
9949,
12,
11890,
5034,
279,
4062,
548,
16,
2254,
5034,
9949,
6275,
13,
3903,
31,
203,
203,
565,
445,
29200,
1235,
12,
11890,
5034,
279,
4062,
548,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
12409,
12,
11890,
5034,
279,
4062,
548,
13,
3903,
31,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
25,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43113/0x3Ca38253E0f4c5640Be3d3458e4aeC4Ad7Bd8902/sources/MasterChef.sol | Update reward variables of the given pool to be up-to-date. | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 trifleReward = multiplier.mul(triflePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
trifle.mint(devAddress, trifleReward.div(10));
trifle.mint(address(this), trifleReward);
pool.accTriflePerShare = pool.accTriflePerShare.add(trifleReward.mul(1e18).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 7,147,510 | [
1,
1891,
19890,
3152,
434,
326,
864,
2845,
358,
506,
731,
17,
869,
17,
712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
2864,
12,
11890,
5034,
389,
6610,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
309,
261,
2629,
18,
2696,
1648,
2845,
18,
2722,
17631,
1060,
1768,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
9953,
3088,
1283,
422,
374,
747,
2845,
18,
9853,
2148,
422,
374,
13,
288,
203,
5411,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
3639,
2254,
5034,
433,
430,
298,
17631,
1060,
273,
15027,
18,
16411,
12,
313,
430,
298,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
3639,
433,
430,
298,
18,
81,
474,
12,
5206,
1887,
16,
433,
430,
298,
17631,
1060,
18,
2892,
12,
2163,
10019,
203,
3639,
433,
430,
298,
18,
81,
474,
12,
2867,
12,
2211,
3631,
433,
430,
298,
17631,
1060,
1769,
203,
3639,
2845,
18,
8981,
1070,
430,
298,
2173,
9535,
273,
2845,
18,
8981,
1070,
430,
298,
2173,
9535,
18,
1289,
12,
313,
430,
298,
17631,
1060,
18,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
203,
2
]
|
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/_equilibria/root/token/types/Token6.sol | * @notice Transfers `amount` tokens from the `benefactor` to the caller @dev Reverts if trying to pull Ether @param self Token to transfer @param benefactor Address to transfer tokens from @param amount Amount of tokens to transfer/ | function pull(Token6 self, address benefactor, UFixed18 amount) internal {
IERC20(Token6.unwrap(self)).safeTransferFrom(benefactor, address(this), toTokenAmount(amount, false));
}
| 1,912,828 | [
1,
1429,
18881,
1375,
8949,
68,
2430,
628,
326,
1375,
70,
4009,
6812,
68,
358,
326,
4894,
225,
868,
31537,
309,
8374,
358,
6892,
512,
1136,
225,
365,
3155,
358,
7412,
225,
27641,
6812,
5267,
358,
7412,
2430,
628,
225,
3844,
16811,
434,
2430,
358,
7412,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6892,
12,
1345,
26,
365,
16,
1758,
27641,
6812,
16,
587,
7505,
2643,
3844,
13,
2713,
288,
203,
3639,
467,
654,
39,
3462,
12,
1345,
26,
18,
318,
4113,
12,
2890,
13,
2934,
4626,
5912,
1265,
12,
70,
4009,
6812,
16,
1758,
12,
2211,
3631,
358,
1345,
6275,
12,
8949,
16,
629,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
/*
* Token has been generated for FREE using https://vittominacori.github.io/erc20-generator/
*
* NOTE: "Contract Source Code Verified (Similar Match)" means that this Token is similar to other tokens deployed
* using the same generator. It is not an issue. It means that you won't need to verify your source code because of
* it is already verified.
*
* DISCLAIMER: GENERATOR'S AUTHOR IS FREE OF ANY LIABILITY REGARDING THE TOKEN AND THE USE THAT IS MADE OF IT.
* The following code is provided under MIT License. Anyone can use it as per their needs.
* The generator's purpose is to make people able to tokenize their ideas without coding or paying for it.
* Source code is well tested and continuously updated to reduce risk of bugs and to introduce language optimizations.
* Anyway the purchase of tokens involves a high degree of risk. Before acquiring tokens, it is recommended to
* carefully weighs all the information and risks detailed in Token owner's Conditions.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/service/ServicePayer.sol
pragma solidity ^0.8.0;
interface IPayable {
function pay(string memory serviceName) external payable;
}
/**
* @title ServicePayer
* @dev Implementation of the ServicePayer
*/
abstract contract ServicePayer {
constructor(address payable receiver, string memory serviceName) payable {
IPayable(receiver).pay{value: msg.value}(serviceName);
}
}
// File: contracts/utils/GeneratorCopyright.sol
pragma solidity ^0.8.0;
/**
* @title GeneratorCopyright
* @dev Implementation of the GeneratorCopyright
*/
contract GeneratorCopyright {
string private constant _GENERATOR = "https://vittominacori.github.io/erc20-generator";
string private _version;
constructor(string memory version_) {
_version = version_;
}
/**
* @dev Returns the token generator tool.
*/
function generator() public pure returns (string memory) {
return _GENERATOR;
}
/**
* @dev Returns the token generator version.
*/
function version() public view returns (string memory) {
return _version;
}
}
// File: contracts/token/ERC20/HelloERC20.sol
pragma solidity ^0.8.0;
/**
* @title HelloERC20
* @author ERC20 Generator (https://vittominacori.github.io/erc20-generator)
* @dev Implementation of the HelloERC20
*/
contract HelloERC20 is ERC20, ServicePayer, GeneratorCopyright("v5.1.0") {
constructor(
string memory name_,
string memory symbol_,
address payable feeReceiver_
) payable ERC20(name_, symbol_) ServicePayer(feeReceiver_, "HelloERC20") {
_mint(_msgSender(), 10000e18);
}
}
| * @title HelloERC20 @dev Implementation of the HelloERC20/ | contract HelloERC20 is ERC20, ServicePayer, GeneratorCopyright("v5.1.0") {
constructor(
string memory name_,
string memory symbol_,
address payable feeReceiver_
) payable ERC20(name_, symbol_) ServicePayer(feeReceiver_, "HelloERC20") {
_mint(_msgSender(), 10000e18);
}
}
| 135,799 | [
1,
18601,
654,
39,
3462,
225,
25379,
434,
326,
20889,
654,
39,
3462,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
20889,
654,
39,
3462,
353,
4232,
39,
3462,
16,
1956,
52,
1773,
16,
10159,
2951,
4083,
2932,
90,
25,
18,
21,
18,
20,
7923,
288,
203,
565,
3885,
12,
203,
3639,
533,
3778,
508,
67,
16,
203,
3639,
533,
3778,
3273,
67,
16,
203,
3639,
1758,
8843,
429,
14036,
12952,
67,
203,
203,
565,
262,
8843,
429,
4232,
39,
3462,
12,
529,
67,
16,
3273,
67,
13,
1956,
52,
1773,
12,
21386,
12952,
67,
16,
315,
18601,
654,
39,
3462,
7923,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
12619,
73,
2643,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
/**
* @title Primitive's Exchange Contract
* @notice A Decentralized Exchange to manage the buying and selling
of Prime Option tokens.
* @author Primitive
*/
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal virtual {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
abstract contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public virtual returns (bytes4);
}
contract ERC721Holder is IERC721Receiver {
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
/**
* @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 {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
/**
* @title Primitive's Instruments
* @author Primitive Finance
*/
library Instruments {
struct Actors {
uint[] mintedTokens;
uint[] deactivatedTokens;
}
/**
* @dev A Prime has these properties.
* @param ace `msg.sender` of the createPrime function.
* @param xis Quantity of collateral asset token.
* @param yak Address of collateral asset token.
* @param zed Purchase price of collateral, denominated in quantity of token z.
* @param wax Address of purchase price asset token.
* @param pow UNIX timestamp of valid time period.
* @param gem Address of payment receiver of token z.
*/
struct Primes {
address ace;
uint256 xis;
address yak;
uint256 zed;
address wax;
uint256 pow;
address gem;
}
/**
* @dev A Prime has these properties.
* @param chain Keccak256 hash of collateral
* asset address, strike asset address, and expiration date.
*/
struct Chain {
bytes4 chain;
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
abstract contract IPool {
function withdrawExercisedEth(address payable _receiver, uint256 _amount) external virtual returns (bool);
function clearLiability(uint256 liability, address strike, uint256 short) external virtual returns (bool);
function exercise(uint256 _long, uint256 _short, address _strike) external payable virtual returns (bool);
function mintPrimeFromPool(
uint256 _long,
uint256 _short,
address _strike,
uint256 _expiration,
address _primeReceiver
) external payable virtual returns (bool);
function getAvailableAssets() public virtual returns (uint256);
}
abstract contract IPrime {
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual;
function createPrime(uint256 _xis, address _yak, uint256 _zed, address _wax, uint256 _pow, address _gem) external virtual returns (bool);
function exercise(uint256 _tokenId) external virtual returns (bool);
function close(uint256 _collateralId, uint256 _burnId) external virtual returns (bool);
function withdraw(uint256 _amount, address _asset) public virtual returns (bool);
function getPrime(uint256 _tokenId) external view virtual returns(
address ace,
uint256 xis,
address yak,
uint256 zed,
address wax,
uint256 pow,
address gem,
bytes4 chain
);
function _primeCompare(uint256 _collateralId, uint256 _burnId) public view virtual returns (bool burn);
function getChain(uint256 _tokenId) external view virtual returns (bytes4 chain);
function isTokenExpired(uint256 _tokenId) public view virtual returns(bool);
}
contract Exchange is ERC721Holder, ReentrancyGuard, Ownable, Pausable {
using SafeMath for uint256;
address public _owner;
address private _primeAddress;
address public _poolAddress;
IPool public _poolInterface;
uint256 public _feePool;
uint256 constant _feeDenomination = 333; /* 0.30% = 0.003 = 1 / 333 */
uint256 constant _poolPremiumDenomination = 5; /* 20% = 0.2 = 1 / 5 - FIX */
event SellOrder(address _seller, uint256 _askPrice, uint256 _tokenId, bool _filled);
event BuyOrder(address _buyer, uint256 _bidPrice, uint256 _tokenId, bool _filled);
event BuyOrderUnfilled(address _buyer, uint256 _bidPrice, uint256 _nonce);
event FillUnfilledBuyOrder(address _seller, uint256 _tokenId);
event FillOrder(address _seller, address _buyer, uint256 _filledPrice, uint256 _tokenId);
event FillOrderFromPool(address _buyer, uint256 _bidPrice, uint256 _amount);
event CloseOrder(address _user, uint256 _tokenId, bool _buyOrder);
event CloseUnfilledBuyOrder(address _user, bytes4 _chain, uint256 _buyOrderNonce);
struct SellOrders {
address payable seller;
uint256 askPrice;
uint256 tokenId;
}
struct BuyOrders {
address payable buyer;
uint256 bidPrice;
uint256 tokenId;
}
struct BuyOrdersUnfilled {
address payable buyer;
uint256 bidPrice;
bytes4 chain;
uint256 xis;
address yak;
uint256 zed;
address wax;
uint256 pow;
}
/* MAPS TOKENIDS WITH SELL ORDER DETAILS */
mapping(uint256 => SellOrders) public _sellOrders;
/* MAPS TOKENIDS WITH BUY ORDER DETAILS */
mapping(uint256 => BuyOrders) public _buyOrders;
/* MAPS HASH OF PROPERTIES TO AN ORDER NONCE THAT RETURNS THE UNFILLED ORDER DETAILS */
mapping(bytes4 => mapping(uint256 => BuyOrdersUnfilled)) public _buyOrdersUnfilled;
/* MAX HEIGHT OF UNFILLED ORDERS */
mapping(bytes4 => uint256) public _unfilledNonce;
/* MAPS USERS TO ETHER BALANCES IN EXCHANGE */
mapping(address => uint256) public _etherBalance;
/* Maps a user to added pool funds */
mapping(address => uint256) private _feePoolContribution;
/* INTIALIZES TOKEN 0 -> ALL ORDERS ARE RESET TO THIS DEFAULT VALUE WHEN FILLED/CLOSED */
constructor(address primeAddress) public {
_primeAddress = primeAddress;
_owner = msg.sender;
_feePool = 0;
_buyOrders[0] = BuyOrders(
address(0),
0,
0
);
_sellOrders[0] = SellOrders(
address(0),
0,
0
);
_buyOrdersUnfilled[0][0] = BuyOrdersUnfilled(
address(0),
0,
0,
0,
address(0),
0,
address(0),
0
);
}
receive() external payable {}
/* SET POOL ADDRESS */
function setPoolAddress(address poolAddress) external onlyOwner {
_poolAddress = poolAddress;
_poolInterface = IPool(poolAddress);
}
/* KILL SWITCH */
function killSwitch() external onlyOwner {
_pause();
}
/* REVIVE */
function unpause() external onlyOwner {
_unpause();
}
/* Prime Address */
function getPrimeAddress() public view returns (address) {
return _primeAddress;
}
/**
* @dev users withdraw ether rather than have it directly sent to them
* @param _amount value of ether to withdraw
*/
function withdrawEther(uint256 _amount) external nonReentrant {
require(_etherBalance[msg.sender] >= _amount, 'Bal < amount');
(bool success, ) = msg.sender.call.value(_amount)("");
require(success, "Transfer failed.");
}
/* CORE MUTATIVE FUNCTIONS */
/**
* @dev List a valid Prime for sale
* @param _tokenId the Prime's nonce when minted
* @param _askPrice value in wei desired as payment
* @return bool Whether or not the tx succeeded
*/
function sellOrder(
uint256 _tokenId,
uint256 _askPrice
)
external
whenNotPaused
returns (bool)
{
IPrime _prime = IPrime(_primeAddress);
/* CHECKS */
require(_tokenId > 0, 'Invalid Token');
require(_askPrice > 0, 'Ask < 0');
_prime.isTokenExpired(_tokenId);
require(!isListed(_tokenId), 'Token listed already');
/* EFFECTS */
/* Gets a buy order request ID if _tokenId has matching properties and can fill order*/
uint256 fillable = checkUnfilledBuyOrders(_tokenId, _askPrice);
/* INTERACTIONS */
/*
If a buy order request matches a token's properties, and the bid price
fulfills the order, fill it
*/
if(fillable > 0) {
/* Unique hash of the Prime's key properties: Asset addresses & expiration date */
bytes4 chain = _prime.getChain(_tokenId);
/* Buy order request of hash 'chain' at order request nonce */
BuyOrdersUnfilled memory _buyUnfilled = _buyOrdersUnfilled[chain][fillable];
return fillUnfilledBuyOrder(
_tokenId,
_buyUnfilled.bidPrice,
_askPrice,
_buyUnfilled.buyer,
msg.sender,
fillable,
chain
);
}
/*
* If a buy order for the _tokenId is available, fill it,
* else, list it for sale and transfer it from user to the dex
*/
if(fillable == 0) {
BuyOrders memory _buy = _buyOrders[_tokenId];
if(_buy.bidPrice >= _askPrice) {
return fillOrder(
false,
_tokenId,
_buy.bidPrice,
_askPrice,
_buy.buyer,
msg.sender
);
} else {
/* Add sell order to state */
_sellOrders[_tokenId] = SellOrders(
msg.sender,
_askPrice,
_tokenId
);
/* Take prime from sender */
_prime.safeTransferFrom(msg.sender, address(this), _tokenId);
emit SellOrder(msg.sender, _askPrice, _tokenId, false);
return true;
}
}
}
/**
* @dev offer a bid for a specific token
* @param _tokenId nonce of token when minted
* @param _bidPrice value offered to purchase Prime
* @return bool whether the tx succeeds
*/
function buyOrder(
uint256 _tokenId,
uint256 _bidPrice
)
public
payable
nonReentrant
whenNotPaused
returns (bool)
{
/* CHECKS */
require(_tokenId > 0, 'Invalid Token');
require(_bidPrice > 0, 'Bid < 0');
uint256 _fee = _bidPrice.div(_feeDenomination);
uint256 _totalCost = _bidPrice.add(_fee);
require(msg.value >= _totalCost, 'Val < cost');
/* Transfer remaining bid to Buyer */
if(msg.value > _totalCost) {
(bool success, ) = msg.sender.call.value(msg.value.sub(_totalCost))("");
require(success, 'Transfer fail.');
}
/* EFFECTS */
SellOrders memory _sell = _sellOrders[_tokenId];
/* INTERACTIONS */
/*
* If the token is listed for sale, fill it
* Else, submit an offer to buy a specific token
*/
if(isListed(_tokenId) && _bidPrice >= _sell.askPrice ) {
return fillOrder(
true,
_tokenId,
_bidPrice,
_sell.askPrice,
msg.sender,
_sell.seller
);
} else {
_buyOrders[_tokenId] = BuyOrders(
msg.sender,
_bidPrice,
_tokenId
);
emit BuyOrder(msg.sender, _bidPrice, _tokenId, false);
return true;
}
}
/**
* @dev fill an order
* @param _buyOrder whether this order is a buy order
* @param _tokenId nonce of Prime when minted
* @param _bidPrice value offered to buy Prime
* @param _askPrice value required to buy Prime
* @param _buyer address of buying party
* @param _seller address of selling party (can be DEX or user)
* @return bool whether the tx succeeds
*/
function fillOrder(
bool _buyOrder,
uint256 _tokenId,
uint256 _bidPrice,
uint256 _askPrice,
address payable _buyer,
address payable _seller
)
private
returns (bool)
{
/* CHECKS */
/* EFFECTS */
/* Clears order from state */
if(_buyOrder) {
emit BuyOrder(_buyer, _bidPrice, _tokenId, true);
clearSellOrder(_tokenId);
} else {
emit SellOrder(_seller, _askPrice, _tokenId, true);
clearBuyOrder(_tokenId);
}
/* Update ether balance state of buyer, seller, and reward pool */
_etherBalance[_seller] = _etherBalance[_seller].add(_askPrice);
uint256 _fee = _bidPrice.div(_feeDenomination);
_feePoolContribution[_seller] = _feePoolContribution[_seller].add(_fee);
_feePool = _feePool.add(_fee);
/* INTERACTIONS */
/*
* IF ITS BUY ORDER - PRIME IS OWNED BY EXCHANGE
* IF ITS SELL ORDER - PRIME IS OWNED BY SELLER
*/
IPrime _prime = IPrime(_primeAddress);
if(_buyOrder) {
_prime.safeTransferFrom(address(this), _buyer, _tokenId);
} else {
_prime.safeTransferFrom(_seller, _buyer, _tokenId);
}
emit FillOrder(_seller, _buyer, _askPrice, _tokenId);
return true;
}
/**
* @dev request to buy a Prime with params
* @param _bidPrice value offered to buy Prime
* @param _xis amount of collateral (underlying) asset
* @param _yak address of collateral ERC-20 token
* @param _zed amount of payment (strike) asset
* @param _wax address of strike ERC-20 token
* @param _pow timestamp of expiration
* @return bool whether the tx suceeds
*/
function buyOrderUnfilled(
uint256 _bidPrice,
/* bytes4 _chain, */
uint256 _xis,
address _yak,
uint256 _zed,
address _wax,
uint256 _pow
)
external
payable
nonReentrant
whenNotPaused
returns (bool)
{
/* CHECKS */
require(_bidPrice > 0, 'Bid < 0');
/* EFFECTS */
/* If the pool can fill the order, mint the Prime from pool */
if(_poolInterface.getAvailableAssets() >= _xis) {
/* FIX with variable premium from Pool - 20% of collateral */
uint256 premiumToPay = _xis.mul(20).div(10**2);
require(_bidPrice >= premiumToPay, 'Bid < premium');
/* Calculate the payment */
uint256 feeOnPayment = premiumToPay.mul(3).div(1000);
uint256 amountNotReturned = premiumToPay.add(feeOnPayment);
/* Update fee pool state */
_feePoolContribution[msg.sender] = _feePoolContribution[msg.sender].add(feeOnPayment);
/* Mint Prime */
_poolInterface.mintPrimeFromPool.value(premiumToPay)(
_xis,
_zed,
_wax,
_pow,
msg.sender
);
emit FillOrderFromPool(msg.sender, _bidPrice, _xis);
/* Transfer remaining bid to Buyer */
if(msg.value > amountNotReturned) {
(bool success,) = msg.sender.call.value(msg.value.sub(amountNotReturned))("");
require(success, 'Transfer fail.');
return success;
}
return true;
}
/* Fee */
uint256 fee = _bidPrice.div(_feeDenomination);
uint256 totalCost = _bidPrice.add(fee);
require(msg.value >= totalCost, 'Val < cost');
/* Get chain data and log the nonce of the order */
bytes4 _chain = bytes4(
keccak256(abi.encodePacked(_yak)))
^ bytes4(keccak256(abi.encodePacked(_wax)))
^ bytes4(keccak256(abi.encodePacked(_pow))
);
uint256 nonce = (_unfilledNonce[_chain]).add(1);
_unfilledNonce[_chain] = nonce;
/* Update Buy Order State */
_buyOrdersUnfilled[_chain][nonce] = BuyOrdersUnfilled(
msg.sender,
_bidPrice,
_chain,
_xis,
_yak,
_zed,
_wax,
_pow
);
emit BuyOrderUnfilled(msg.sender, _bidPrice, _unfilledNonce[_chain]);
/* Return any remaining bid to Buyer */
if(msg.value > totalCost) {
(bool success, ) = msg.sender.call.value(msg.value.sub(totalCost))("");
require(success, 'Transfer fail.');
return success;
}
return true;
}
/**
* @dev compares tokenID properties with requested buy order
* @param _tokenId nonce of Prime when minted
* @return uint256 unfilled buy order nonce, returns 0 if none found
*/
function checkUnfilledBuyOrders(
uint256 _tokenId,
uint256 _askPrice
)
public
view
returns (uint256)
{
IPrime _prime = IPrime(_primeAddress);
address ace;
uint256 xis;
address yak;
uint256 zed;
address wax;
uint256 pow;
address gem;
bytes4 chain;
chain = _prime.getChain(_tokenId);
(ace, xis, yak, zed, wax, pow, gem, ) = _prime.getPrime(_tokenId);
bytes32 primeHash = keccak256(
abi.encodePacked(
xis,
yak,
zed,
wax,
pow
)
);
for(uint i = 1; i <= _unfilledNonce[chain]; i++) {
BuyOrdersUnfilled memory _buyObj = _buyOrdersUnfilled[chain][i];
bytes32 buyHash = keccak256(
abi.encodePacked(
_buyObj.xis,
_buyObj.yak,
_buyObj.zed,
_buyObj.wax,
_buyObj.pow
)
);
if(primeHash == buyHash && _buyObj.bidPrice >= _askPrice) {
return i;
}
}
return 0;
}
/**
* @dev fills a sell order using an unfilled buy order
* @param _tokenId nonce of Prime when minted
* @param _bidPrice value of offer
* @param _askPrice value in wei that the seller requires
* @param _buyer address of buyer
* @param _seller address of seller
* @param _buyOrderNonce nonce when buy order request was submitted
* @param _chain hash of asset 1 address + asset 2 address + expiration
* @return bool whether or not the tx succeeded
*/
function fillUnfilledBuyOrder(
uint256 _tokenId,
uint256 _bidPrice,
uint256 _askPrice,
address payable _buyer,
address payable _seller,
uint256 _buyOrderNonce,
bytes4 _chain
)
private
nonReentrant
returns (bool)
{
/* CHECKS */
/* EFFECTS */
/* Clears the buy order request from state */
clearUnfilledBuyOrder(_chain, _buyOrderNonce);
/* Updates state of the user's ether balance in the dex */
_etherBalance[_seller] = _etherBalance[_seller].add(_askPrice);
uint256 _fee = _bidPrice.div(_feeDenomination);
_feePoolContribution[_seller] = _feePoolContribution[_seller].add(_fee);
_feePool = _feePool.add(_fee);
/* INTERACTIONS */
/* Transfers the Prime to the buyer */
IPrime _prime = IPrime(_primeAddress);
_prime.safeTransferFrom(_seller, _buyer, _tokenId);
emit SellOrder(_seller, _askPrice, _tokenId, true);
emit FillUnfilledBuyOrder(_seller, _tokenId);
return true;
}
/**
* @dev changes state of order to 0
* @param _tokenId nonce of Prime when minted
*/
function clearSellOrder(uint256 _tokenId) internal {
_sellOrders[_tokenId] = _sellOrders[0];
}
/**
* @dev changes state of order to 0
* @param _tokenId nonce of Prime when minted
*/
function clearBuyOrder(uint256 _tokenId) internal {
/* CLEARS BUY ORDER */
_buyOrders[_tokenId] = _buyOrders[0];
}
/**
* @dev changes state of order to 0
* @param _chain hash of asset 1 address + asset 2 address + expiration
* @param _buyOrderNonce nonce of buy order request
*/
function clearUnfilledBuyOrder(bytes4 _chain, uint256 _buyOrderNonce) internal {
_buyOrdersUnfilled[_chain][_buyOrderNonce] = _buyOrdersUnfilled[0][0];
}
/**
* @dev clears a sell order from state and returns funds/assets
* @param _tokenId nonce of Prime when minted
* @return bool whether the tx succeeds
*/
function closeSellOrder(uint256 _tokenId) external nonReentrant returns (bool) {
SellOrders memory _sells = _sellOrders[_tokenId];
/* CHECKS */
require(_tokenId > 0, 'Invalid Token');
require(msg.sender == _sells.seller, 'Msg.sender != seller');
/* EFFECTS */
clearSellOrder(_tokenId);
/* INTERACTIONS */
IPrime _prime = IPrime(_primeAddress);
_prime.safeTransferFrom(address(this), _sells.seller, _tokenId);
emit CloseOrder(msg.sender, _tokenId, false);
return true;
}
/**
* @dev clears a buy order from state and returns funds/assets
* @param _tokenId nonce of Prime when minted
* @return bool whether the tx succeeds
*/
function closeBuyOrder(uint256 _tokenId) external nonReentrant returns (bool) {
BuyOrders memory _buys = _buyOrders[_tokenId];
/* CHECKS */
require(_tokenId > 0, 'Invalid Token');
require(msg.sender == _buys.buyer, 'Msg.sender != buyer');
/* EFFECTS */
/* Clear buy order state */
clearBuyOrder(_tokenId);
/* Update user's withdrawable ether balance */
_etherBalance[_buys.buyer].add(_buys.bidPrice);
/* INTERACTIONS */
emit CloseOrder(msg.sender, _tokenId, true);
return true;
}
/**
* @dev clears an unfilled buy order from state and returns funds/assets
* @param _chain keccak256 hash of asset 1 address ^ asset 2 Address ^ expiration
* @param _buyOrderNonce nonce of when buy order was submitted
* @return bool whether the tx succeeds
*/
function closeUnfilledBuyOrder(
bytes4 _chain,
uint256 _buyOrderNonce
)
external
nonReentrant
returns (bool)
{
/* Buy order request of hash 'chain' at order request nonce */
BuyOrdersUnfilled memory _buyUnfilled = _buyOrdersUnfilled[_chain][_buyOrderNonce];
/* CHECKS */
require(msg.sender == _buyUnfilled.buyer, 'Msg.sender != buyer');
/* EFFECTS */
/* Clears the buy order request from state */
clearUnfilledBuyOrder(_chain, _buyOrderNonce);
/* Update user's withdrawable ether balance */
_etherBalance[_buyUnfilled.buyer].add(_buyUnfilled.bidPrice);
/* INTERACTIONS */
emit CloseUnfilledBuyOrder(msg.sender, _chain, _buyOrderNonce);
return true;
}
/* VIEW FUNCTIONS */
function getFeesGenerated(address payable _user) public view returns(uint256) {
return _etherBalance[_user];
}
function getBuyOrder(uint256 _tokenId)
public
view
returns(
address payable buyer,
uint256 bidPrice,
uint256 tokenId
)
{
BuyOrders memory _buys = _buyOrders[_tokenId];
return (
_buys.buyer,
_buys.bidPrice,
_buys.tokenId
);
}
function getSellOrder(uint256 _tokenId)
public
view
returns(
address payable seller,
uint256 askPrice,
uint256 tokenId
)
{
SellOrders memory _sells = _sellOrders[_tokenId];
return (
_sells.seller,
_sells.askPrice,
_sells.tokenId
);
}
function isListed(uint256 _tokenId) public view returns(bool) {
SellOrders memory _sells = _sellOrders[_tokenId];
return _sells.seller != address(0);
}
} | SET POOL ADDRESS */ | function setPoolAddress(address poolAddress) external onlyOwner {
_poolAddress = poolAddress;
_poolInterface = IPool(poolAddress);
}
| 13,010,075 | [
1,
4043,
13803,
1741,
11689,
10203,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
2864,
1887,
12,
2867,
2845,
1887,
13,
3903,
1338,
5541,
288,
203,
3639,
389,
6011,
1887,
273,
2845,
1887,
31,
203,
3639,
389,
6011,
1358,
273,
467,
2864,
12,
6011,
1887,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-04-12
*/
// File: contracts\gsn\Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts\access\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\libs\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
// 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts\token\erc20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\token\erc20\ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
string private _name;
string private _symbol;
uint8 private _decimals;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: 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 returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount));
}
}
// File: contracts\libs\RealMath.sol
pragma solidity ^0.5.0;
/**
* Reference: https://github.com/balancer-labs/balancer-core/blob/master/contracts/BNum.sol
*/
library RealMath {
uint256 private constant BONE = 10 ** 18;
uint256 private constant MIN_BPOW_BASE = 1 wei;
uint256 private constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint256 private constant BPOW_PRECISION = BONE / 10 ** 10;
/**
* @dev
*/
function rtoi(uint256 a)
internal
pure
returns (uint256)
{
return a / BONE;
}
/**
* @dev
*/
function rfloor(uint256 a)
internal
pure
returns (uint256)
{
return rtoi(a) * BONE;
}
/**
* @dev
*/
function radd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
/**
* @dev
*/
function rsub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
(uint256 c, bool flag) = rsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
/**
* @dev
*/
function rsubSign(uint256 a, uint256 b)
internal
pure
returns (uint256, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
/**
* @dev
*/
function rmul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
return c1 / BONE;
}
/**
* @dev
*/
function rdiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL");
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL");
return c1 / b;
}
/**
* @dev
*/
function rpowi(uint256 a, uint256 n)
internal
pure
returns (uint256)
{
uint256 z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = rmul(a, a);
if (n % 2 != 0) {
z = rmul(z, a);
}
}
return z;
}
/**
* @dev Computes b^(e.w) by splitting it into (b^e)*(b^0.w).
* Use `rpowi` for `b^e` and `rpowK` for k iterations of approximation of b^0.w
*/
function rpow(uint256 base, uint256 exp)
internal
pure
returns (uint256)
{
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint256 whole = rfloor(exp);
uint256 remain = rsub(exp, whole);
uint256 wholePow = rpowi(base, rtoi(whole));
if (remain == 0) {
return wholePow;
}
uint256 partialResult = rpowApprox(base, remain, BPOW_PRECISION);
return rmul(wholePow, partialResult);
}
/**
* @dev
*/
function rpowApprox(uint256 base, uint256 exp, uint256 precision)
internal
pure
returns (uint256)
{
(uint256 x, bool xneg) = rsubSign(base, BONE);
uint256 a = exp;
uint256 term = BONE;
uint256 sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i = 1--> k) * x ^ k) / (k!)
// Each iteration, multiply previous term by (a - (k - 1)) * x / k
// continue until term is less than precision
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BONE;
(uint256 c, bool cneg) = rsubSign(a, rsub(bigK, BONE));
term = rmul(term, rmul(c, x));
term = rdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = rsub(sum, term);
} else {
sum = radd(sum, term);
}
}
return sum;
}
}
// File: contracts\libs\Address.sol
pragma solidity ^0.5.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 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));
}
}
// File: contracts\pak\ICollection.sol
pragma solidity ^0.5.0;
interface ICollection {
// ERC721
function transferFrom(address from, address to, uint256 tokenId) external;
// ERC1155
function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes calldata data) external;
}
// File: contracts\pak\ASH.sol
pragma solidity ^0.5.0;
contract ASH is Ownable, ERC20 {
using RealMath for uint256;
using Address for address;
bytes4 private constant _ERC1155_RECEIVED = 0xf23a6e61;
event CollectionWhitelist(address collection, bool status);
event AssetWhitelist(address collection, uint256 assetId, bool status);
event CollectionBlacklist(address collection, bool status);
event AssetBlacklist(address collection, uint256 assetId, bool status);
event Swapped(address collection, uint256 assetId, address account, uint256 amount, bool isWhitelist, bool isERC721);
// Mapping "collection" whitelist
mapping(address => bool) private _collectionWhitelist;
// Mapping "asset" whitelist
mapping(address => mapping(uint256 => bool)) private _assetWhitelist;
// Mapping "collection" blacklist
mapping(address => bool) private _collectionBlacklist;
// Mapping "asset" blacklist
mapping(address => mapping(uint256 => bool)) private _assetBlacklist;
bool public isStarted = false;
bool public isERC721Paused = false;
bool public isERC1155Paused = true;
/**
* @dev Throws if NFT swapping does not start yet
*/
modifier started() {
require(isStarted, "ASH: NFT swapping does not start yet");
_;
}
/**
* @dev Throws if collection or asset is in blacklist
*/
modifier notInBlacklist(address collection, uint256 assetId) {
require(!_collectionBlacklist[collection] && !_assetBlacklist[collection][assetId], "ASH: collection or asset is in blacklist");
_;
}
/**
* @dev Initializes the contract settings
*/
constructor(string memory name, string memory symbol)
public
ERC20(name, symbol, 18)
{}
/**
* @dev Starts to allow NFT swapping
*/
function start()
public
onlyOwner
{
isStarted = true;
}
/**
* @dev Pauses NFT (everything) swapping
*/
function pause(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = true;
} else {
isERC1155Paused = true;
}
}
/**
* @dev Resumes NFT (everything) swapping
*/
function resume(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = false;
} else {
isERC1155Paused = false;
}
}
/**
* @dev Adds or removes collections in whitelist
*/
function updateWhitelist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionWhitelist[collection] != status) {
_collectionWhitelist[collection] = status;
emit CollectionWhitelist(collection, status);
}
}
}
/**
* @dev Adds or removes assets in whitelist
*/
function updateWhitelist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetWhitelist[collection][assetId] != status) {
_assetWhitelist[collection][assetId] = status;
emit AssetWhitelist(collection, assetId, status);
}
}
}
/**
* @dev Returns true if collection is in whitelist
*/
function isWhitelist(address collection)
public
view
returns (bool)
{
return _collectionWhitelist[collection];
}
/**
* @dev Returns true if asset is in whitelist
*/
function isWhitelist(address collection, uint256 assetId)
public
view
returns (bool)
{
return _assetWhitelist[collection][assetId];
}
/**
* @dev Adds or removes collections in blacklist
*/
function updateBlacklist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionBlacklist[collection] != status) {
_collectionBlacklist[collection] = status;
emit CollectionBlacklist(collection, status);
}
}
}
/**
* @dev Adds or removes assets in blacklist
*/
function updateBlacklist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetBlacklist[collection][assetId] != status) {
_assetBlacklist[collection][assetId] = status;
emit AssetBlacklist(collection, assetId, status);
}
}
}
/**
* @dev Returns true if collection is in blacklist
*/
function isBlacklist(address collection)
public
view
returns (bool)
{
return _collectionBlacklist[collection];
}
/**
* @dev Returns true if asset is in blacklist
*/
function isBlacklist(address collection, uint256 assetId)
public
view
returns (bool)
{
return _assetBlacklist[collection][assetId];
}
/**
* @dev Burns tokens with a specific `amount`
*/
function burn(uint256 amount)
public
{
_burn(_msgSender(), amount);
}
/**
* @dev Calculates token amount that user will receive when burn
*/
function calculateToken(address collection, uint256 assetId)
public
view
returns (bool, uint256)
{
bool whitelist = false;
// Checks if collection or asset in whitelist
if (_collectionWhitelist[collection] || _assetWhitelist[collection][assetId]) {
whitelist = true;
}
uint256 exp = totalSupply().rdiv(1000000 * (10 ** 18));
uint256 multiplier = RealMath.rdiv(1, 2).rpow(exp);
uint256 result;
// Calculates token amount that will issue
if (whitelist) {
result = multiplier.rmul(1000 * (10 ** 18));
} else {
result = multiplier.rmul(multiplier).rmul(2 * (10 ** 18));
}
return (whitelist, result);
}
/**
* @dev Issues ERC20 tokens
*/
function _issueToken(address collection, uint256 assetId, address account, bool isERC721)
private
{
(bool whitelist, uint256 amount) = calculateToken(collection, assetId);
if (!whitelist) {
if (isERC721) {
require(!isERC721Paused, "ASH: ERC721 swapping paused");
} else {
require(!isERC1155Paused, "ASH: ERC1155 swapping paused");
}
}
require(amount > 0, "ASH: amount is invalid");
// Issues tokens
_mint(account, amount);
emit Swapped(collection, assetId, account, amount, whitelist, isERC721);
}
/**
* @dev Swaps ERC721 to ERC20
*/
function swapERC721(address collection, uint256 assetId)
public
started()
notInBlacklist(collection, assetId)
{
address msgSender = _msgSender();
require(!msgSender.isContract(), "ASH: caller is invalid");
// Transfers ERC721 and lock in this smart contract
ICollection(collection).transferFrom(msgSender, address(this), assetId);
// Issues ERC20 tokens for caller
_issueToken(collection, assetId, msgSender, true);
}
/**
* @dev Swaps ERC1155 to ERC20
*/
function swapERC1155(address collection, uint256 assetId)
public
started()
notInBlacklist(collection, assetId)
{
address msgSender = _msgSender();
require(!msgSender.isContract(), "ASH: caller is invalid");
// Transfers ERC1155 and lock in this smart contract
ICollection(collection).safeTransferFrom(msgSender, address(this), assetId, 1, "");
// Issues ERC20 tokens for caller
_issueToken(collection, assetId, msgSender, false);
}
function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data)
external
returns (bytes4)
{
return _ERC1155_RECEIVED;
}
} | * @dev Adds or removes assets in blacklist/ | function updateBlacklist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetBlacklist[collection][assetId] != status) {
_assetBlacklist[collection][assetId] = status;
emit AssetBlacklist(collection, assetId, status);
}
}
}
| 15,284,315 | [
1,
3655,
578,
7157,
7176,
316,
11709,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
25811,
12,
2867,
8526,
3778,
6980,
16,
2254,
5034,
8526,
3778,
3310,
2673,
16,
1426,
1267,
13,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
2254,
5034,
769,
273,
6980,
18,
2469,
31,
203,
203,
3639,
2583,
12,
2469,
422,
3310,
2673,
18,
2469,
16,
315,
10793,
30,
769,
434,
5352,
353,
486,
3959,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
769,
31,
277,
27245,
288,
203,
5411,
1758,
1849,
273,
6980,
63,
77,
15533,
203,
5411,
2254,
5034,
3310,
548,
273,
3310,
2673,
63,
77,
15533,
203,
203,
5411,
309,
261,
67,
9406,
25811,
63,
5548,
6362,
9406,
548,
65,
480,
1267,
13,
288,
203,
7734,
389,
9406,
25811,
63,
5548,
6362,
9406,
548,
65,
273,
1267,
31,
203,
203,
7734,
3626,
10494,
25811,
12,
5548,
16,
3310,
548,
16,
1267,
1769,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
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 = true;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/**
* @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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(0X0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract BlockableToken is Ownable{
event Blocked(address blockedAddress);
event UnBlocked(address unBlockedAddress);
//keep mapping of blocked addresses
mapping (address => bool) public blockedAddresses;
modifier whenNotBlocked(){
require(!blockedAddresses[msg.sender]);
_;
}
function blockAddress(address toBeBlocked) onlyOwner public {
blockedAddresses[toBeBlocked] = true;
emit Blocked(toBeBlocked);
}
function unBlockAddress(address toBeUnblocked) onlyOwner public {
blockedAddresses[toBeUnblocked] = false;
emit UnBlocked(toBeUnblocked);
}
}
contract StrikeToken is MintableToken, Pausable, BlockableToken{
string public name = "Dimensions Strike Token";
string public symbol = "DST";
uint256 public decimals = 18;
event Ev(string message, address whom, uint256 val);
struct XRec {
bool inList;
address next;
address prev;
uint256 val;
}
struct QueueRecord {
address whom;
uint256 val;
}
address first = 0x0;
address last = 0x0;
mapping (address => XRec) public theList;
QueueRecord[] theQueue;
// add a record to the END of the list
function add(address whom, uint256 value) internal {
theList[whom] = XRec(true,0x0,last,value);
if (last != 0x0) {
theList[last].next = whom;
} else {
first = whom;
}
last = whom;
emit Ev("add",whom,value);
}
function remove(address whom) internal {
if (first == whom) {
first = theList[whom].next;
theList[whom] = XRec(false,0x0,0x0,0);
return;
}
address next = theList[whom].next;
address prev = theList[whom].prev;
if (prev != 0x0) {
theList[prev].next = next;
}
if (next != 0x0) {
theList[next].prev = prev;
}
theList[whom] =XRec(false,0x0,0x0,0);
emit Ev("remove",whom,0);
}
function update(address whom, uint256 value) internal {
if (value != 0) {
if (!theList[whom].inList) {
add(whom,value);
} else {
theList[whom].val = value;
emit Ev("update",whom,value);
}
return;
}
if (theList[whom].inList) {
remove(whom);
}
}
/**
* @dev Allows anyone to transfer the Strike tokens once trading has started
* @param _to the recipient address of the tokens.
* @param _value number of tokens to be transfered.
*/
function transfer(address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) {
bool result = super.transfer(_to, _value);
update(msg.sender,balances[msg.sender]);
update(_to,balances[_to]);
return result;
}
/**
* @dev Allows anyone to transfer the Strike tokens once trading has started
* @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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) {
bool result = super.transferFrom(_from, _to, _value);
update(_from,balances[_from]);
update(_to,balances[_to]);
return result;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
bool result = super.mint(_to,_amount);
update(_to,balances[_to]);
return result;
}
constructor() public{
owner = msg.sender;
}
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract StrikeTokenCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
StrikeToken public token = new StrikeToken();
// start and end times
uint256 public startTimestamp = 1575158400;
uint256 public endTimestamp = 1577750400;
uint256 etherToWei = 10**18;
// address where funds are collected and tokens distributed
address public hardwareWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B;
address public restrictedWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B;
address public additionalTokensFromCommonPoolWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B;
mapping (address => uint256) public deposits;
uint256 public numberOfPurchasers;
// Percentage bonus tokens given in Token Sale, on a daily basis
uint256[] public bonus = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
uint256 public rate = 4800; // 4800 DST is one Ether
// amount of raised money in wei
uint256 public weiRaised = 0;
uint256 public tokensSold = 0;
uint256 public advisorTokensGranted = 0;
uint256 public commonPoolTokensGranted = 0;
uint256 public minContribution = 100 * 1 finney;
uint256 public hardCapEther = 30000;
uint256 hardcap = hardCapEther * etherToWei;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event MainSaleClosed();
uint256 public weiRaisedInPresale = 0 ether;
bool private frozen = false;
function freeze() public onlyOwner{
frozen = true;
}
function unfreeze() public onlyOwner{
frozen = false;
}
modifier whenNotFrozen() {
require(!frozen);
_;
}
modifier whenFrozen() {
require(frozen);
_;
}
function setHardwareWallet(address _wallet) public onlyOwner {
require(_wallet != 0x0);
hardwareWallet = _wallet;
}
function setRestrictedWallet(address _restrictedWallet) public onlyOwner {
require(_restrictedWallet != 0x0);
restrictedWallet = _restrictedWallet;
}
function setAdditionalTokensFromCommonPoolWallet(address _wallet) public onlyOwner {
require(_wallet != 0x0);
additionalTokensFromCommonPoolWallet = _wallet;
}
function setHardCapEther(uint256 newEtherAmt) public onlyOwner{
require(newEtherAmt > 0);
hardCapEther = newEtherAmt;
hardcap = hardCapEther * etherToWei;
}
constructor() public {
require(startTimestamp >= now);
require(endTimestamp >= startTimestamp);
}
// check if valid purchase
modifier validPurchase {
require(now >= startTimestamp);
require(now < endTimestamp);
require(msg.value >= minContribution);
require(frozen == false);
_;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
if (now > endTimestamp)
return true;
return false;
}
// low level token purchase function
function buyTokens(address beneficiary) public payable validPurchase {
require(beneficiary != 0x0);
uint256 weiAmount = msg.value;
// Check if the hardcap has been exceeded
uint256 weiRaisedSoFar = weiRaised.add(weiAmount);
require(weiRaisedSoFar + weiRaisedInPresale <= hardcap);
if (deposits[msg.sender] == 0) {
numberOfPurchasers++;
}
deposits[msg.sender] = weiAmount.add(deposits[msg.sender]);
uint256 daysInSale = (now - startTimestamp) / (1 days);
uint256 thisBonus = 0;
if(daysInSale < 29 ){
thisBonus = bonus[daysInSale];
}
// Calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
uint256 extraBonus = tokens.mul(thisBonus);
extraBonus = extraBonus.div(100);
tokens = tokens.add(extraBonus);
// Update the global token sale variables
uint256 finalTokenCount;
finalTokenCount = tokens.add(tokensSold);
weiRaised = weiRaisedSoFar;
tokensSold = finalTokenCount;
token.mint(beneficiary, tokens);
hardwareWallet.transfer(msg.value);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
function grantTokensAdvisors(address beneficiary,uint256 dstTokenCount) public onlyOwner{
dstTokenCount = dstTokenCount * etherToWei;
advisorTokensGranted = advisorTokensGranted.add(dstTokenCount);
token.mint(beneficiary,dstTokenCount);
}
function grantTokensCommonPool(address beneficiary,uint256 dstTokenCount) public onlyOwner{
dstTokenCount = dstTokenCount * etherToWei;
commonPoolTokensGranted = commonPoolTokensGranted.add(dstTokenCount);
token.mint(beneficiary,dstTokenCount);
}
// finish mining coins and transfer ownership of Change coin to owner
function finishMinting() public onlyOwner returns(bool){
require(hasEnded());
uint issuedTokenSupply = token.totalSupply();
uint publicTokens = issuedTokenSupply-advisorTokensGranted;
if(publicTokens>60*advisorTokensGranted/40 ){
uint restrictedTokens=(publicTokens)*40/60-advisorTokensGranted;
token.mint(restrictedWallet, restrictedTokens);
advisorTokensGranted=advisorTokensGranted+restrictedTokens;
}
else if(publicTokens<60*advisorTokensGranted/40){
uint256 deltaCommonPool=advisorTokensGranted*60/40-publicTokens;
token.mint(additionalTokensFromCommonPoolWallet,deltaCommonPool);
}
token.finishMinting();
token.transferOwnership(owner);
emit MainSaleClosed();
return true;
}
// fallback function can be used to buy tokens
function () payable public {
buyTokens(msg.sender);
}
function setRate(uint256 amount) onlyOwner public {
require(amount>=0);
rate = amount;
}
function setBonus(uint256 [] amounts) onlyOwner public {
require( amounts.length > 30 );
bonus = amounts;
}
function setWeiRaisedInPresale(uint256 amount) onlyOwner public {
require(amount>=0);
weiRaisedInPresale = amount;
}
function setEndTimeStamp(uint256 end) onlyOwner public {
require(end>now);
endTimestamp = end;
}
function setStartTimeStamp(uint256 start) onlyOwner public {
startTimestamp = start;
}
function pauseTrading() onlyOwner public{
token.pause();
}
function startTrading() onlyOwner public{
token.unpause();
}
function smartBlockAddress(address toBeBlocked) onlyOwner public{
token.blockAddress(toBeBlocked);
}
function smartUnBlockAddress(address toBeUnblocked) onlyOwner public{
token.unBlockAddress(toBeUnblocked);
}
function changeTokenOwner(address newOwner) public onlyOwner {
require(hasEnded());
token.changeOwner(newOwner);
}
function bulkGrantTokenAdvisors(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{
require( beneficiaries.length == granttokencounts.length);
for (uint256 i=0; i<beneficiaries.length; i++) {
grantTokensAdvisors(beneficiaries[i],granttokencounts[i]);
}
}
function bulkGrantTokenCommonPool(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{
require( beneficiaries.length == granttokencounts.length);
for (uint256 i=0; i<beneficiaries.length; i++) {
grantTokensCommonPool(beneficiaries[i],granttokencounts[i]);
}
}
} | * @dev Allows anyone to transfer the Strike tokens once trading has started @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 uint the amout of tokens to be transfered/ | function transferFrom(address _from, address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) {
bool result = super.transferFrom(_from, _to, _value);
update(_from,balances[_from]);
update(_to,balances[_to]);
return result;
}
| 1,769,249 | [
1,
19132,
1281,
476,
358,
7412,
326,
3978,
2547,
2430,
3647,
1284,
7459,
711,
5746,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
326,
2125,
659,
434,
2430,
358,
506,
7412,
329,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
13,
1071,
1347,
1248,
28590,
1347,
1248,
23722,
1135,
261,
6430,
13,
288,
203,
3639,
1426,
563,
273,
2240,
18,
13866,
1265,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
1089,
24899,
2080,
16,
70,
26488,
63,
67,
2080,
19226,
203,
3639,
1089,
24899,
869,
16,
70,
26488,
63,
67,
869,
19226,
203,
3639,
327,
563,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
contract PunkCity is ERC1155 {
struct User {
string name;
string hometown;
string country;
}
User user;
string public name = "Punk Cities";
uint256 public placeId;
uint256 private energy;
uint256 private chip;
// the use of constant is not coherent if there can be more than one upgrade possible
uint256 constant public energyPerPlaceTreshold = 2;
uint256 constant public chipPerPlaceTreshold = 2;
uint256 constant public verificationPerPlaceTreshold = 2;
address[] public registeredUsers;
enum Type {
Basketball_court,
Bus_Stop,
City_Hall,
Cityzen_Theater,
Community_center,
Fireman_Station,
Hospital,
Kids_playground,
Landmark,
Open_air_gym,
Police_Station,
Public_Park,
Soccer_court,
Stadium,
Temple,
Art_Gallery,
Beach,
Bike_Road,
Camping_site,
Museum,
Recycling_can,
Skate_Park,
Library,
University,
Coworking_space,
Industrial_Park,
Tech_company,
Technology_Cluster
}
enum Quest {
Solarpunk,
Cyberpunk
}
struct Place {
Type placeType;
address registerAddress;
uint256 verificationTimes;
uint256 energyPerPlace;
uint256 chipPerPlace;
uint256 placeIdLevel;
}
Place place;
mapping(address => User) public addressToUserDetail;
mapping(address => bool) public userRegistered;
mapping(uint => Place) public placeIdToPlaceDetail;
mapping(address => uint256) public energyPerAddress;
mapping(address => uint256) public chipPerAddress;
mapping(address => mapping(uint256 => bool)) public verifiersPerPlaceId;
mapping(address => mapping(uint256 => Quest)) public playerQuestTypePerPlaceId;
mapping(address => mapping(uint256 => uint256)) public playerEnergyDepositedPerPlaceId;
mapping(address => mapping(uint256 => uint256)) public playerChipDepositedPerPlaceId;
mapping (uint256 => string) uris;
modifier isUserRegistered(address _address) {
require(userRegistered[_address], "This user is not registered");
_;
}
// this modifier doesn't look like a solid solution. doesn't work with place id 0
modifier placeIdExists(uint256 _placeId) {
require(_placeId <= placeId, "This place id doesn't exist");
_;
}
event PlaceCreated(address indexed _from, uint256 _placeId, uint256 _questType, uint256 _placeType);
event PlaceVerified(address indexed _from, uint256 _placeId, uint256 _questType);
event EnergyTransfer(address indexed _from, uint256 _placeId);
event ChipTransfer(address indexed _from, uint256 _placeId);
constructor() ERC1155("") {
placeId = 0;
}
/**
* @dev Registering user in the game
*/
function registerUser(string memory _name, string memory _hometown, string memory _country) public {
require(userRegistered[msg.sender] == false, "You are already registered");
userRegistered[msg.sender] = true;
registeredUsers.push(msg.sender);
addressToUserDetail[msg.sender].name = _name;
addressToUserDetail[msg.sender].hometown = _hometown;
addressToUserDetail[msg.sender].country = _country;
}
/**
* @dev User is registering a place in the game
*/
function registerPlace(uint256 _placeType, uint256 _questType, string memory _ipfsuri) public isUserRegistered(msg.sender) {
// updating the place struct
placeIdToPlaceDetail[placeId].placeType = Type(_placeType);
placeIdToPlaceDetail[placeId].registerAddress = msg.sender;
// updating players' mappings
//placeIdToRegisterAddress[placeId] = msg.sender;
verifiersPerPlaceId[msg.sender][placeId] = true;
playerQuestTypePerPlaceId[msg.sender][placeId] = Quest(_questType);
// user gets one energy point for registering place
if (_questType == 0) {
energyPerAddress[msg.sender] += 1;
} else {
chipPerAddress[msg.sender] += 1;
}
//registration results in the place being minted as an nft. the nft id will be the same as the placeId
mint(msg.sender, placeId, 1, "");
setTokenUri(placeId, _ipfsuri);
emit PlaceCreated(msg.sender, placeId, _questType, _placeType);
emit EnergyTransfer(msg.sender, placeId);
placeId += 1;
}
/**
* @dev User is verifying a place in the game. Place register is not allowed to verify its own place
*/
function verifyPlace(uint256 _placeId, uint256 _questType) public isUserRegistered(msg.sender) {
require(_placeId < placeId, "This placeId doesn't exist yet");
require(verifiersPerPlaceId[msg.sender][_placeId] == false, "You can't verify twice");
placeIdToPlaceDetail[_placeId].verificationTimes += 1;
//placeIdToVerificationTimes[_placeId] += 1;
if (_questType == 0) {
energyPerAddress[msg.sender] += 1;
} else {
chipPerAddress[msg.sender] += 1;
}
// mappings updated. with this we know the address that verify a certain place id
verifiersPerPlaceId[msg.sender][_placeId] = true;
playerQuestTypePerPlaceId[msg.sender][_placeId] = Quest(_questType);
emit PlaceVerified(msg.sender, _placeId, _questType );
emit EnergyTransfer(msg.sender, _placeId);
}
//WARNING! just for the sake of testing.
function transferEnergyAndchips(address _to, uint256 _energy, uint256 _chips) public {
energyPerAddress[_to] += _energy;
chipPerAddress[_to] += _chips;
}
function depositEnergy(uint256 _placeId, uint256 _energy) public placeIdExists(_placeId) {
require(energyPerAddress[msg.sender] >= _energy, "You don't have enough energy");
// track how much was deposited
playerEnergyDepositedPerPlaceId[msg.sender][_placeId] += _energy;
placeIdToPlaceDetail[_placeId].energyPerPlace += _energy;
//energyPerPlace[_placeId] += _energy;
energyPerAddress[msg.sender] -= _energy;
emit EnergyTransfer(msg.sender, _placeId);
}
function depositChip(uint256 _placeId, uint256 _chips) public placeIdExists(_placeId) {
require(chipPerAddress[msg.sender] >= _chips, "You don't have enough chips");
// track how much was deposited
playerChipDepositedPerPlaceId[msg.sender][_placeId] += _chips;
placeIdToPlaceDetail[_placeId].chipPerPlace += _chips;
chipPerAddress[msg.sender] -= _chips;
emit ChipTransfer(msg.sender, _placeId);
}
/**
* @dev User can upgrade a place after some conditions are met. As a result, rewards are shared among verifiers
*/
function assignReward(address _player, uint256 _placeId) public view returns(uint256, uint256) {
uint256 energyReward = 0;
uint256 chipReward = 0;
energyReward = playerEnergyDepositedPerPlaceId[_player][_placeId] * 2;
chipReward = playerChipDepositedPerPlaceId[_player][_placeId] * 2;
return(energyReward, chipReward);
}
function upgradePlace(uint256 _placeId) public placeIdExists(_placeId) {
require(placeIdToPlaceDetail[_placeId].verificationTimes >= verificationPerPlaceTreshold, "This place can't be upgraded because there are not enough verifications");
require(placeIdToPlaceDetail[_placeId].energyPerPlace >= energyPerPlaceTreshold, "This place can't be upgraded because there is not enough energy deposited");
require(placeIdToPlaceDetail[_placeId].chipPerPlace >= chipPerPlaceTreshold, "This place can't be upgraded because there are not enough chips deposited");
//to check functionality: require(verifiersPerPlaceId[msg.sender][_placeId] == true, "Only verifiers of this place can upgrade it");
// new nfts of the same token id are minted and shared amond verifiers.
mint(msg.sender, _placeId, placeIdToPlaceDetail[_placeId].verificationTimes, "");
// calculate rewards
address[] memory verifiers = getVerifiers(_placeId);
for(uint i = 0; i < verifiers.length; i++) {
// an nft should not be sent to the regster
if(verifiers[i] == placeIdToPlaceDetail[_placeId].registerAddress) {
if(verifiers[i] == msg.sender) {
// person that upgrades receives 5x the units deposited
uint256 energyReward = playerEnergyDepositedPerPlaceId[verifiers[i]][_placeId] * 5;
uint256 chipReward = playerChipDepositedPerPlaceId[verifiers[i]][_placeId] * 5;
energyPerAddress[verifiers[i]] += (energyReward + 1);
chipPerAddress[verifiers[i]] += (chipReward + 1);
} else {
// verifiers received double the amount of units deposited after upgrade
(uint256 energyReward1, uint256 chipReward1) = assignReward(verifiers[i], _placeId);
energyPerAddress[verifiers[i]] += (energyReward1 + 1);
chipPerAddress[verifiers[i]] += (chipReward1 + 1);
}
} else {
safeTransferFrom(msg.sender, verifiers[i], _placeId, 1, "");
if(verifiers[i] == msg.sender) {
// person that upgrades receives 5x the units deposited
uint256 energyReward = playerEnergyDepositedPerPlaceId[verifiers[i]][_placeId] * 5;
uint256 chipReward = playerChipDepositedPerPlaceId[verifiers[i]][_placeId] * 5;
energyPerAddress[verifiers[i]] += (energyReward + 1);
chipPerAddress[verifiers[i]] += (chipReward + 1);
} else {
// verifiers received double the amount of units deposited after upgrade
(uint256 energyReward1, uint256 chipReward1) = assignReward(verifiers[i], _placeId);
energyPerAddress[verifiers[i]] += (energyReward1 + 1);
chipPerAddress[verifiers[i]] += (chipReward1 + 1);
}
}
}
//upgrade next level
placeIdToPlaceDetail[_placeId].placeIdLevel += 1;
}
function getVerifiers(uint256 _placeId) public view returns(address[] memory) {
//adding 1 because register is also added among the verifiers
address[] memory result = new address[](placeIdToPlaceDetail[_placeId].verificationTimes + 1);
uint counter = 0;
for (uint256 i = 0; i < registeredUsers.length; i++) {
if(verifiersPerPlaceId[registeredUsers[i]][_placeId] == true) {
result[counter] = (registeredUsers[i]);
counter++;
}
}
return result;
}
function getPlaceIdPerAddress() public view returns(uint256[] memory) {
uint256[] memory result = new uint256[](placeId);
uint counter = 0;
for (uint256 i = 0; i < placeId; i++) {
if(placeIdToPlaceDetail[i].registerAddress == msg.sender) {
result[counter] = (i);
counter++;
}
}
return result;
}
// Minting and metadata
function mint(address account, uint256 id, uint256 amount, bytes memory data)
private
{
_mint(account, id, amount, data);
}
function uri(uint256 _tokenId) override public view returns (string memory) {
return(uris[_tokenId]);
}
function setTokenUri(uint256 _tokenId, string memory _uri) internal {
require(bytes(uris[_tokenId]).length == 0, "Cannot set uri twice");
uris[_tokenId] = _uri;
}
} | placeIdToVerificationTimes[_placeId] += 1; | function verifyPlace(uint256 _placeId, uint256 _questType) public isUserRegistered(msg.sender) {
require(_placeId < placeId, "This placeId doesn't exist yet");
require(verifiersPerPlaceId[msg.sender][_placeId] == false, "You can't verify twice");
placeIdToPlaceDetail[_placeId].verificationTimes += 1;
if (_questType == 0) {
energyPerAddress[msg.sender] += 1;
chipPerAddress[msg.sender] += 1;
}
playerQuestTypePerPlaceId[msg.sender][_placeId] = Quest(_questType);
emit PlaceVerified(msg.sender, _placeId, _questType );
emit EnergyTransfer(msg.sender, _placeId);
}
| 7,246,249 | [
1,
964,
28803,
13483,
10694,
63,
67,
964,
548,
65,
1011,
404,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3929,
6029,
12,
11890,
5034,
389,
964,
548,
16,
2254,
5034,
389,
456,
559,
13,
1071,
29302,
10868,
12,
3576,
18,
15330,
13,
288,
203,
203,
3639,
2583,
24899,
964,
548,
411,
3166,
548,
16,
315,
2503,
3166,
548,
3302,
1404,
1005,
4671,
8863,
203,
3639,
2583,
12,
502,
3383,
2173,
6029,
548,
63,
3576,
18,
15330,
6362,
67,
964,
548,
65,
422,
629,
16,
315,
6225,
848,
1404,
3929,
13605,
8863,
203,
203,
3639,
3166,
28803,
6029,
6109,
63,
67,
964,
548,
8009,
27726,
10694,
1011,
404,
31,
203,
203,
203,
3639,
309,
261,
67,
456,
559,
422,
374,
13,
288,
203,
5411,
12929,
2173,
1887,
63,
3576,
18,
15330,
65,
1011,
404,
31,
203,
5411,
18624,
2173,
1887,
63,
3576,
18,
15330,
65,
1011,
404,
31,
203,
3639,
289,
1377,
203,
203,
3639,
7291,
30791,
559,
2173,
6029,
548,
63,
3576,
18,
15330,
6362,
67,
964,
548,
65,
273,
4783,
395,
24899,
456,
559,
1769,
7010,
203,
3639,
3626,
13022,
24369,
12,
3576,
18,
15330,
16,
389,
964,
548,
16,
389,
456,
559,
11272,
203,
3639,
3626,
512,
1224,
7797,
5912,
12,
3576,
18,
15330,
16,
389,
964,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
import "../../Libraries/introspection/ERC165.sol";
import "../Interface/IERCX.sol";
import "../../Libraries/utils/Address.sol";
import "../../Libraries/math/SafeMath.sol";
import "../../Libraries/drafts/Counters.sol";
import "../Interface/IERCXReceiver.sol";
// import './MinterRole.sol';
contract ERCX is ERC165, IERCX {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
bytes4 private constant _ERCX_RECEIVED = 0x11111111;
//bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"));
// Mapping from item ID to layer to owner
mapping(uint256 => mapping(uint256 => address)) private _itemOwner;
// Mapping from item ID to layer to approved address
mapping(uint256 => mapping(uint256 => address)) private _transferApprovals;
// Mapping from owner to layer to number of owned item
mapping(address => mapping(uint256 => Counters.Counter)) private _ownedItemsCount;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Mapping from item ID to approved address of setting lien
mapping(uint256 => address) private _lienApprovals;
// Mapping from item ID to contract address of lien
mapping(uint256 => address) private _lienAddress;
// Mapping from item ID to approved address of setting tenant right agreement
mapping(uint256 => address) private _tenantRightApprovals;
// Mapping from item ID to contract address of TenantRight
mapping(uint256 => address) private _tenantRightAddress;
bytes4 private constant _InterfaceId_ERCX = bytes4(
keccak256("balanceOfOwner(address)")
) ^
bytes4(keccak256("balanceOfUser(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("userOf(uint256)")) ^
bytes4(keccak256("safeTransferOwner(address, address, uint256)")) ^
bytes4(
keccak256("safeTransferOwner(address, address, uint256, bytes)")
) ^
bytes4(keccak256("safeTransferUser(address, address, uint256)")) ^
bytes4(
keccak256("safeTransferUser(address, address, uint256, bytes)")
) ^
bytes4(keccak256("approveForOwner(address, uint256)")) ^
bytes4(keccak256("getApprovedForOwner(uint256)")) ^
bytes4(keccak256("approveForUser(address, uint256)")) ^
bytes4(keccak256("getApprovedForUser(uint256)")) ^
bytes4(keccak256("setApprovalForAll(address, bool)")) ^
bytes4(keccak256("isApprovedForAll(address, address)")) ^
bytes4(keccak256("approveLien(address, uint256)")) ^
bytes4(keccak256("getApprovedLien(uint256)")) ^
bytes4(keccak256("setLien(uint256)")) ^
bytes4(keccak256("getCurrentLien(uint256)")) ^
bytes4(keccak256("revokeLien(uint256)")) ^
bytes4(keccak256("approveTenantRight(address, uint256)")) ^
bytes4(keccak256("getApprovedTenantRight(uint256)")) ^
bytes4(keccak256("setTenantRight(uint256)")) ^
bytes4(keccak256("getCurrentTenantRight(uint256)")) ^
bytes4(keccak256("revokeTenantRight(uint256)"));
constructor() public {
// register the supported interfaces to conform to ERCX via ERC165
_registerInterface(_InterfaceId_ERCX);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount of items owned by the passed address in the specified layer
*/
function balanceOfOwner(address owner) public view returns (uint256) {
require(owner != address(0));
uint256 balance = _ownedItemsCount[owner][2].current();
return balance;
}
/**
* @dev Gets the balance of the specified address
* @param user address to query the balance of
* @return uint256 representing the amount of items owned by the passed address
*/
function balanceOfUser(address user) public view returns (uint256) {
require(user != address(0));
uint256 balance = _ownedItemsCount[user][1].current();
return balance;
}
/**
* @dev Gets the user of the specified item ID
* @param itemId uint256 ID of the item to query the user of
* @return owner address currently marked as the owner of the given item ID
*/
function userOf(uint256 itemId) public view returns (address) {
address user = _itemOwner[itemId][1];
require(user != address(0));
return user;
}
/**
* @dev Gets the owner of the specified item ID
* @param itemId uint256 ID of the item to query the owner of
* @return owner address currently marked as the owner of the given item ID
*/
function ownerOf(uint256 itemId) public view returns (address) {
address owner = _itemOwner[itemId][2];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the user of the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
*/
function approveForUser(address to, uint256 itemId) public {
address user = userOf(itemId);
address owner = ownerOf(itemId);
require(to != owner && to != user);
require(
msg.sender == user ||
msg.sender == owner ||
isApprovedForAll(user, msg.sender) ||
isApprovedForAll(owner, msg.sender)
);
if (msg.sender == owner || isApprovedForAll(owner, msg.sender)) {
require(getCurrentTenantRight(itemId) == address(0));
}
_transferApprovals[itemId][1] = to;
emit ApprovalForUser(user, to, itemId);
}
/**
* @dev Gets the approved address for the user of the item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval of
* @return address currently approved for the given item ID
*/
function getApprovedForUser(uint256 itemId) public view returns (address) {
require(_exists(itemId, 1));
return _transferApprovals[itemId][1];
}
/**
* @dev Approves another address to transfer the owner of the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
* @param itemId uint256 ID of the item to be approved
*/
function approveForOwner(address to, uint256 itemId) public {
address owner = ownerOf(itemId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_transferApprovals[itemId][2] = to;
emit ApprovalForOwner(owner, to, itemId);
}
/**
* @dev Gets the approved address for the of the item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval o
* @return address currently approved for the given item ID
*/
function getApprovedForOwner(uint256 itemId) public view returns (address) {
require(_exists(itemId, 2),"no owner approval set");
return _transferApprovals[itemId][2];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all items 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 Approves another address to set lien contract for the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
* @param itemId uint256 ID of the item to be approved
*/
function approveLien(address to, uint256 itemId) public {
address owner = ownerOf(itemId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_lienApprovals[itemId] = to;
emit LienApproval(to, itemId);
}
/**
* @dev Gets the approved address for setting lien for a item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval of
* @return address currently approved for the given item ID
*/
function getApprovedLien(uint256 itemId) public view returns (address) {
require(_exists(itemId, 2));
return _lienApprovals[itemId];
}
/**
* @dev Sets lien agreements to already approved address
* The lien address is allowed to transfer all items of the sender on their behalf
* @param itemId uint256 ID of the item
*/
function setLien(uint256 itemId) public {
require(msg.sender == getApprovedLien(itemId));
_lienAddress[itemId] = msg.sender;
_clearLienApproval(itemId);
emit LienSet(msg.sender, itemId, true);
}
/**
* @dev Gets the current lien agreement address, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the lien address
* @return address of the lien agreement address for the given item ID
*/
function getCurrentLien(uint256 itemId) public view returns (address) {
require(_exists(itemId, 2));
return _lienAddress[itemId];
}
/**
* @dev Revoke the lien agreements. Only the lien address can revoke.
* @param itemId uint256 ID of the item
*/
function revokeLien(uint256 itemId) public {
require(msg.sender == getCurrentLien(itemId));
_lienAddress[itemId] = address(0);
emit LienSet(address(0), itemId, false);
}
/**
* @dev Approves another address to set tenant right agreement for the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
* @param itemId uint256 ID of the item to be approved
*/
function approveTenantRight(address to, uint256 itemId) public {
address owner = ownerOf(itemId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tenantRightApprovals[itemId] = to;
emit TenantRightApproval(to, itemId);
}
/**
* @dev Gets the approved address for setting tenant right for a item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval of
* @return address currently approved for the given item ID
*/
function getApprovedTenantRight(uint256 itemId)
public
view
returns (address)
{
require(_exists(itemId, 2));
return _tenantRightApprovals[itemId];
}
/**
* @dev Sets the tenant right agreement to already approved address
* The lien address is allowed to transfer all items of the sender on their behalf
* @param itemId uint256 ID of the item
*/
function setTenantRight(uint256 itemId) public {
require(msg.sender == getApprovedTenantRight(itemId));
_tenantRightAddress[itemId] = msg.sender;
_clearTenantRightApproval(itemId);
_clearTransferApproval(itemId, 1); //Reset transfer approval
emit TenantRightSet(msg.sender, itemId, true);
}
/**
* @dev Gets the current tenant right agreement address, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the tenant right address
* @return address of the tenant right agreement address for the given item ID
*/
function getCurrentTenantRight(uint256 itemId)
public
view
returns (address)
{
require(_exists(itemId, 2));
return _tenantRightAddress[itemId];
}
/**
* @dev Revoke the tenant right agreement. Only the lien address can revoke.
* @param itemId uint256 ID of the item
*/
function revokeTenantRight(uint256 itemId) public {
require(msg.sender == getCurrentTenantRight(itemId));
_tenantRightAddress[itemId] = address(0);
emit TenantRightSet(address(0), itemId, false);
}
/**
* @dev Safely transfers the user of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(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 item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
*/
function safeTransferUser(address from, address to, uint256 itemId) public {
// solium-disable-next-line arg-overflow
safeTransferUser(from, to, itemId, "");
}
/**
* @dev Safely transfers the user of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(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 item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferUser(
address from,
address to,
uint256 itemId,
bytes memory data
) public {
require(_isEligibleForTransfer(msg.sender, itemId, 1));
_safeTransfer(from, to, itemId, 1, data);
}
/**
* @dev Safely transfers the ownership of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(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 item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
*/
function safeTransferOwner(address from, address to, uint256 itemId)
public
{
// solium-disable-next-line arg-overflow
safeTransferOwner(from, to, itemId, "");
}
/**
* @dev Safely transfers the ownership of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(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 item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferOwner(
address from,
address to,
uint256 itemId,
bytes memory data
) public {
require(_isEligibleForTransfer(msg.sender, itemId, 2));
_safeTransfer(from, to, itemId, 2, data);
}
/**
* @dev Safely transfers the ownership of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(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 item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
* @param data bytes data to send along with a safe transfer check
*/
function _safeTransfer(
address from,
address to,
uint256 itemId,
uint256 layer,
bytes memory data
) internal {
_transfer(from, to, itemId, layer);
require(
_checkOnERCXReceived(from, to, itemId, layer, data),
"ERCX: transfer to non ERCXReceiver implementer"
);
}
/**
* @dev Returns whether the given spender can transfer a given item ID.
* @param spender address of the spender to query
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
* @return bool whether the msg.sender is approved for the given item ID,
* is an operator of the owner, or is the owner of the item
*/
function _isEligibleForTransfer(
address spender,
uint256 itemId,
uint256 layer
) internal view returns (bool) {
require(_exists(itemId, layer));
if (layer == 1) {
address user = userOf(itemId);
address owner = ownerOf(itemId);
require(
spender == user ||
spender == owner ||
isApprovedForAll(user, spender) ||
isApprovedForAll(owner, spender) ||
spender == getApprovedForUser(itemId) ||
spender == getCurrentLien(itemId)
);
if (spender == owner || isApprovedForAll(owner, spender)) {
require(getCurrentTenantRight(itemId) == address(0));
}
return true;
}
if (layer == 2) {
address owner = ownerOf(itemId);
require(
spender == owner ||
isApprovedForAll(owner, spender) ||
spender == getApprovedForOwner(itemId) ||
spender == getCurrentLien(itemId)
);
return true;
}
}
/**
* @dev Returns whether the specified item exists
* @param itemId uint256 ID of the item to query the existence of
* @param layer uint256 number to specify the layer
* @return whether the item exists
*/
function _exists(uint256 itemId, uint256 layer)
internal
view
returns (bool)
{
address owner = _itemOwner[itemId][layer];
return owner != address(0);
}
/**
* @dev Internal function to safely mint a new item.
* Reverts if the given item ID already exists.
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted item
* @param itemId uint256 ID of the item to be minted
*/
function _safeMint(address to, uint256 itemId) internal {
_safeMint(to, itemId, "");
}
/**
* @dev Internal function to safely mint a new item.
* Reverts if the given item ID already exists.
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted item
* @param itemId uint256 ID of the item to be minted
* @param data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 itemId, bytes memory data) internal {
_mint(to, itemId);
require(_checkOnERCXReceived(address(0), to, itemId, 1, data));
require(_checkOnERCXReceived(address(0), to, itemId, 2, data));
}
/**
* @dev Internal function to mint a new item.
* Reverts if the given item ID already exists.
* A new item iss minted with all three layers.
* @param to The address that will own the minted item
* @param itemId uint256 ID of the item to be minted
*/
function _mint(address to, uint256 itemId) internal {
require(to != address(0), "ERCX: mint to the zero address");
require(!_exists(itemId, 1), "ERCX: item already minted");
_itemOwner[itemId][1] = to;
_itemOwner[itemId][2] = to;
_ownedItemsCount[to][1].increment();
_ownedItemsCount[to][2].increment();
emit TransferUser(address(0), to, itemId, msg.sender);
emit TransferOwner(address(0), to, itemId, msg.sender);
}
/**
* @dev Internal function to burn a specific item.
* Reverts if the item does not exist.
* @param itemId uint256 ID of the item being burned
*/
function _burn(uint256 itemId) internal {
address user = userOf(itemId);
address owner = ownerOf(itemId);
require(user == msg.sender && owner == msg.sender);
_clearTransferApproval(itemId, 1);
_clearTransferApproval(itemId, 2);
_ownedItemsCount[user][1].decrement();
_ownedItemsCount[owner][2].decrement();
_itemOwner[itemId][1] = address(0);
_itemOwner[itemId][2] = address(0);
emit TransferUser(user, address(0), itemId, msg.sender);
emit TransferOwner(owner, address(0), itemId, msg.sender);
}
/**
* @dev Internal function to transfer ownership of a given item ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
*/
function _transfer(address from, address to, uint256 itemId, uint256 layer)
internal
{
if (layer == 1) {
require(userOf(itemId) == from);
} else {
require(ownerOf(itemId) == from);
}
require(to != address(0));
_clearTransferApproval(itemId, layer);
if (layer == 2) {
_clearLienApproval(itemId);
_clearTenantRightApproval(itemId);
}
_ownedItemsCount[from][layer].decrement();
_ownedItemsCount[to][layer].increment();
_itemOwner[itemId][layer] = to;
if (layer == 1) {
emit TransferUser(from, to, itemId, msg.sender);
} else {
emit TransferOwner(from, to, itemId, msg.sender);
}
}
/**
* @dev Internal function to invoke {IERCXReceiver-onERCXReceived} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERCX` contract and its use is deprecated.
* @param from address representing the previous owner of the given item ID
* @param to target address that will receive the items
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERCXReceived(
address from,
address to,
uint256 itemId,
uint256 layer,
bytes memory data
) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERCXReceiver(to).onERCXReceived(
msg.sender,
from,
itemId,
layer,
data
);
return (retval == _ERCX_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given item ID.
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
*/
function _clearTransferApproval(uint256 itemId, uint256 layer) private {
if (_transferApprovals[itemId][layer] != address(0)) {
_transferApprovals[itemId][layer] = address(0);
}
}
function _clearTenantRightApproval(uint256 itemId) private {
if (_tenantRightApprovals[itemId] != address(0)) {
_tenantRightApprovals[itemId] = address(0);
}
}
function _clearLienApproval(uint256 itemId) private {
if (_lienApprovals[itemId] != address(0)) {
_lienApprovals[itemId] = address(0);
}
}
}
| * @dev Gets the current lien agreement address, or zero if no address set Reverts if the item ID does not exist. @param itemId uint256 ID of the item to query the lien address @return address of the lien agreement address for the given item ID/ | function getCurrentLien(uint256 itemId) public view returns (address) {
require(_exists(itemId, 2));
return _lienAddress[itemId];
}
| 917,046 | [
1,
3002,
326,
783,
4501,
275,
19602,
1758,
16,
578,
3634,
309,
1158,
1758,
444,
868,
31537,
309,
326,
761,
1599,
1552,
486,
1005,
18,
225,
18424,
2254,
5034,
1599,
434,
326,
761,
358,
843,
326,
4501,
275,
1758,
327,
1758,
434,
326,
4501,
275,
19602,
1758,
364,
326,
864,
761,
1599,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5175,
28762,
275,
12,
11890,
5034,
18424,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
1726,
548,
16,
576,
10019,
203,
3639,
327,
389,
549,
275,
1887,
63,
1726,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x874b5d6476F214e37f042Cfc555C07fE99c6D83E/sources/StablePlaza.sol | admin with exchange (un)lock power
| address public admin; | 3,966,591 | [
1,
3666,
598,
7829,
261,
318,
13,
739,
7212,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
1758,
1071,
3981,
31,
17311,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-Identifier: MIT
pragma solidity >= 0.5.17;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity\contracts\ownership\Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: node_modules\multi-token-standard\contracts\interfaces\IERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas
* @param _interfaceId The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// File: node_modules\multi-token-standard\contracts\utils\SafeMath.sol
/**
* @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, "SafeMath#mul: OVERFLOW");
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, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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, "SafeMath#sub: UNDERFLOW");
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, "SafeMath#add: OVERFLOW");
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, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
// File: node_modules\multi-token-standard\contracts\interfaces\IERC1155TokenReceiver.sol
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// File: node_modules\multi-token-standard\contracts\interfaces\IERC1155.sol
interface IERC1155 {
// Events
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev MUST emit when the URI is updated for a token ID
* URIs are defined in RFC 3986
* The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema"
*/
event URI(string _amount, uint256 indexed _id);
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator);
}
// File: node_modules\multi-token-standard\contracts\utils\Address.sol
/**
* Copyright 2018 ZeroEx Intl.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
/**
* @notice Contract that handles metadata related methods.
* @dev Methods assume a deterministic generation of URI based on token IDs.
* Methods also assume that URI uses hex representation of token IDs.
*/
contract ERC1155Metadata {
// URI's default URI prefix
string internal baseMetadataURI;
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Metadata Public Function s |
|__________________________________*/
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* Token IDs are assumed to be represented in their hex format in URIs
* @return URI string
*/
function uri(uint256 _id) public view returns (string memory) {
return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json"));
}
/***********************************|
| Metadata Internal Functions |
|__________________________________*/
/**
* @notice Will emit default URI log event for corresponding token _id
* @param _tokenIDs Array of IDs of tokens to log default URI
*/
function _logURIs(uint256[] memory _tokenIDs) internal {
string memory baseURL = baseMetadataURI;
string memory tokenURI;
for (uint256 i = 0; i < _tokenIDs.length; i++) {
tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json"));
emit URI(tokenURI, _tokenIDs[i]);
}
}
/**
* @notice Will emit a specific URI log event for corresponding token
* @param _tokenIDs IDs of the token corresponding to the _uris logged
* @param _URIs The URIs of the specified _tokenIDs
*/
function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal {
require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH");
for (uint256 i = 0; i < _tokenIDs.length; i++) {
emit URI(_URIs[i], _tokenIDs[i]);
}
}
/**
* @notice Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal {
baseMetadataURI = _newBaseMetadataURI;
}
/***********************************|
| Utility Internal Functions |
|__________________________________*/
/**
* @notice Convert uint256 to string
* @param _i Unsigned integer to convert to string
*/
function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 ii = _i;
uint256 len;
// Get number of bytes
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
// Get each individual ASCII
while (ii != 0) {
bstr[k--] = byte(uint8(48 + ii % 10));
ii /= 10;
}
// Convert to string
return string(bstr);
}
}
// File: node_modules\multi-token-standard\contracts\tokens\ERC1155\ERC1155.sol
/**
* @dev Implementation of Multi-Token Standard contract
*/
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
// File: multi-token-standard\contracts\tokens\ERC1155\ERC1155MintBurn.sol
/**
* @dev Multi-Fungible Tokens with minting and burning methods. These methods assume
* a parent contract to be executed as they are `internal` functions
*/
contract ERC1155MintBurn is ERC1155 {
/****************************************|
| Minting Functions |
|_______________________________________*/
/**
* @notice Mint _amount of tokens of a given id
* @param _to The address to mint tokens to
* @param _id Token id to mint
* @param _amount The amount to be minted
* @param _data Data to pass if receiver is contract
*/
function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Add _amount
balances[_to][_id] = balances[_to][_id].add(_amount);
// Emit event
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
// Calling onReceive method if recipient is contract
_callonERC1155Received(address(0x0), _to, _id, _amount, _data);
}
/**
* @notice Mint tokens for each ids in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _amounts Array of amount of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH");
// Number of mints to execute
uint256 nMint = _ids.length;
// Executing all minting
for (uint256 i = 0; i < nMint; i++) {
// Update storage balance
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit batch mint event
emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts);
// Calling onReceive method if recipient is contract
_callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data);
}
/****************************************|
| Burning Functions |
|_______________________________________*/
/**
* @notice Burn _amount of tokens of a given token id
* @param _from The address to burn tokens from
* @param _id Token id to burn
* @param _amount The amount to be burned
*/
function _burn(address _from, uint256 _id, uint256 _amount)
internal
{
//Substract _amount
balances[_from][_id] = balances[_from][_id].sub(_amount);
// Emit event
emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount);
}
/**
* @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair
* @param _from The address to burn tokens from
* @param _ids Array of token ids to burn
* @param _amounts Array of the amount to be burned
*/
function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH");
// Number of mints to execute
uint256 nBurn = _ids.length;
// Executing all minting
for (uint256 i = 0; i < nBurn; i++) {
// Update storage balance
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
}
// Emit batch mint event
emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts);
}
}
// File: contracts\Strings.sol
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function indexOf(string memory _base, string memory _value)
internal
pure
returns (int) {
return _indexOf(_base, _value, 0);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string starting
* from a defined offset
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @param _offset The starting point to start searching from which can start
* from 0, but must not exceed the length of the string
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function _indexOf(string memory _base, string memory _value, uint _offset)
internal
pure
returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for (uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
}
// File: contracts\ERC1155Tradable.sol
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
//address proxyRegistryAddress;
uint256 private totalTokenAssets = 10000;
uint256 private totalReserve = 336;
uint256 public _currentTokenID = 0;
uint256 public _customizedTokenId = 9000;
// uint256 private _maxTokenPerUser = 1000;
uint256 private _maxTokenPerMint = 2;
uint256 public sold = 0;
uint256 private reserved = 0;
// uint256 private presalesMaxToken = 3;
uint256 private preSalesPrice1 = 0.07 ether;
uint256 private preSalesPrice2 = 0.088 ether;
uint256 private publicSalesPrice = 0.088 ether;
uint256 private preSalesMaxSupply3 = 9000;
address private signerAddress = 0x22A19Fd9F3a29Fe8260F88C46dB04941Fa0615C9;
uint16 public salesStage = 3; //1-presales1 , 2-presales2 , 3-public
address payable public companyWallet = 0xE369C3f00d8dc97Be4B58a7ede901E48c4767bD2; //test
mapping(uint256 => uint256) private _presalesPrice;
mapping(address => uint256) public presales1minted; // To check how many tokens an address has minted during presales
mapping(address => uint256) public presales2minted; // To check how many tokens an address has minted during presales
mapping(address => uint256) public minted; // To check how many tokens an address has minted
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
mapping(uint256 => string) public rawdata;
event TokenMinted(uint indexed _tokenid, address indexed _userAddress, string indexed _rawData);
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol
//address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
//proxyRegistryAddress = _proxyRegistryAddress;
}
using Strings for string;
// // Function to receive Ether. msg.data must be empty
// receive() external payable {}
// // Fallback function is called when msg.data is not empty
// fallback() external payable {}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function reserve( //When start this mint 336 first
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
require(reserved + _initialSupply <= totalReserve, "Reserve Empty");
sold += _initialSupply;
for (uint256 i = 0; i < _initialSupply; i++) {
reserved++;
uint256 _id = reserved;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
creators[_id] = msg.sender;
_mint(_initialOwner, _id, 1, _data);
tokenSupply[_id] = 1;
}
return 0;
}
function toBytes(address a) public pure returns (bytes memory b){
assembly {
let m := mload(0x40)
a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
function addressToString(address _addr) internal pure returns(string memory) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];
str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
function toAsciiString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(
bytes1 b
) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
bytes memory bytesArray = new bytes(64);
for (i = 0; i < bytesArray.length; i++) {
uint8 _f = uint8(_bytes32[i/2] & 0x0f);
uint8 _l = uint8(_bytes32[i/2] >> 4);
bytesArray[i] = toByte(_f);
i = i + 1;
bytesArray[i] = toByte(_l);
}
return string(bytesArray);
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function splitSignature(bytes memory sig)
public
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function recoverSigner(bytes32 message, bytes memory sig)
public
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
function isValidData(string memory _word, bytes memory sig) public view returns(bool){
bytes32 message = keccak256(abi.encodePacked(_word));
return (recoverSigner(message, sig) == signerAddress);
}
function toByte(uint8 _uint8) public pure returns (byte) {
if(_uint8 < 10) {
return byte(_uint8 + 48);
} else {
return byte(_uint8 + 87);
}
}
function withdraw() public onlyOwner {
require(companyWallet != address(0), "Please Set Company Wallet Address");
uint256 balance = address(this).balance;
companyWallet.transfer(balance);
}
function presales(
address _initialOwner,
uint256 _initialSupply,
bytes calldata _sig,
bytes calldata _data
) external payable returns (uint256) {
require(salesStage == 1 || salesStage == 2, "Presales is closed");
if(salesStage == 1){
require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 1");
require(_initialSupply * preSalesPrice1 == msg.value, "Invalid Fund");
}else if(salesStage == 2){
require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 2");
require(_initialSupply * preSalesPrice2 == msg.value, "Invalid Fund");
}
require(isValidData(addressToString(msg.sender), _sig), addressToString(msg.sender));
sold += _initialSupply;
if(salesStage == 1){
presales1minted[_initialOwner] += _initialSupply;
}else if(salesStage == 2){
presales2minted[_initialOwner] += _initialSupply;
}
minted[_initialOwner] += _initialSupply;
for (uint256 i = 0; i < _initialSupply; i++) {
uint256 _id = _getNextTokenID() + totalReserve;
_incrementTokenTypeId();
creators[_id] = msg.sender;
_mint(_initialOwner, _id, 1, _data);
tokenSupply[_id] = 1;
emit TokenMinted(_id, _initialOwner, "");
}
return 0;
}
function publicsales(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external payable returns (uint256) {
require(salesStage == 3 , "Public Sales Is Closed");
require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token reached for Sales Stage 3");
require(_initialSupply * publicSalesPrice == msg.value , "Invalid Fund");
sold += _initialSupply;
minted[_initialOwner] += _initialSupply;
for (uint256 i = 0; i < _initialSupply; i++) {
uint256 _id = _getNextTokenID() + totalReserve;
_incrementTokenTypeId();
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
creators[_id] = msg.sender;
_mint(_initialOwner, _id, 1, _data);
tokenSupply[_id] = 1;
emit TokenMinted(_id, _initialOwner, "");
}
return 0;
}
function CustomizedSales(
address _initialOwner,
uint256 _initialSupply,
string calldata _rawdata,
bytes calldata _sig,
bytes calldata _data,
uint price
) external payable returns (uint256) {
string memory data = Strings.strConcat(_rawdata, _uint2str(price));
require(isValidData(data, _sig), "Invalid Signature");
uint temp_id = _getNextCustomizedTokenID();
require(temp_id + _initialSupply -1 <= totalTokenAssets, "Max Token Minted");
require(msg.value == price, "Invalid fund");
for (uint256 i = 0; i < _initialSupply; i++) {
uint256 _id = _getNextCustomizedTokenID();
_incrementCustomizedTokenTypeId();
creators[_id] = msg.sender;
_mint(_initialOwner, _id, 1, _data);
tokenSupply[_id] = 1;
rawdata[_id] = _rawdata;
emit TokenMinted(_id, _initialOwner, _rawdata);
}
return 0;
}
function setSalesStage(
uint16 stage
) public onlyOwner {
salesStage = stage;
}
function setCompanyWallet(
address payable newWallet
) public onlyOwner {
companyWallet = newWallet;
}
function ownerMint(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
require(sold + _initialSupply <= preSalesMaxSupply3, "Max Token Minted");
sold += _initialSupply;
for (uint256 i = 0; i < _initialSupply; i++) {
uint256 _id = _getNextTokenID() + totalReserve;
_incrementTokenTypeId();
//uint256 _id = reserved;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
creators[_id] = msg.sender;
_mint(_initialOwner, _id, 1, _data);
tokenSupply[_id] = 1;
}
return 0;
}
function walletbalance(
) public view returns (uint256) {
return address(this).balance;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id].add(quantity);
}
_batchMint(_to, _ids, _quantities, _data);
}
function setPrice(uint _sale1, uint _sale2, uint _salepublic) external onlyOwner{
preSalesPrice1 = _sale1;
preSalesPrice2 = _sale2;
publicSalesPrice = _salepublic;
}
/**
* @dev Change the creator address for given tokens
* @param _to Address of the new creator
* @param _ids Array of Token IDs to change creator
*/
function setCreator(
address _to,
uint256[] memory _ids
) public {
require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS.");
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
/**
* @dev Change the creator address for given token
* @param _to Address of the new creator
* @param _id Token IDs to change creator of
*/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id)
{
creators[_id] = _to;
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev calculates the next token ID based on value of _customizedTokenId
* @return uint256 for the next token ID
*/
function _getNextCustomizedTokenID() private view returns (uint256) {
return _customizedTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
/**
* @dev increments the value of _customizedTokenId
*/
function _incrementCustomizedTokenTypeId() private {
_customizedTokenId++;
}
}
// File: contracts\MyCollectible.sol
/**
* @title MyCollectible
* MyCollectible - a contract for my semi-fungible tokens.
*/
contract HypedHuskyMetaCityNFT is ERC1155Tradable {
constructor(string memory _name)//address _proxyRegistryAddress)
ERC1155Tradable(
_name,
"HHMC"
) public {
_setBaseMetadataURI("https://api.HypedHuskyMetaCityNFT.io/nft/");
}
} | * @dev Require msg.sender to own more than 0 of the token id/ | modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol
| 10,160,359 | [
1,
8115,
1234,
18,
15330,
358,
4953,
1898,
2353,
374,
434,
326,
1147,
612,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
25937,
3386,
12,
11890,
5034,
389,
350,
13,
288,
203,
3639,
2583,
12,
70,
26488,
63,
3576,
18,
15330,
6362,
67,
350,
65,
405,
374,
16,
315,
654,
39,
2499,
2539,
1609,
17394,
7,
995,
414,
3386,
30,
20747,
67,
51,
5665,
11367,
67,
16852,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TicTokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
// 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 notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*/
function TicTokenERC20() public {
totalSupply =10000000000000000; // Update total supply with the decimal amount
balanceOf[msg.sender] = 10000000000000000; // Give the creator all initial tokens
name = "The Incremental Chain"; // Set the name for display purposes
symbol = "TIC"; // 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
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* 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 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 on your behalf
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on 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
*/
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
*/
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;
}
} | * Constructor function/ | function TicTokenERC20() public {
}
| 12,155,360 | [
1,
6293,
445,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
399,
335,
1345,
654,
39,
3462,
1435,
1071,
288,
203,
377,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* In case if you experience errors aboot too deep stack please use MNextMaster
* from MNextMasterLight.sol.
*
* It performs less checks which means less security on one hand but
* compatibility with common configured EVMs like this of Ethereum ecosystem
* on the other hand.
*
* To see the differences please read the leading comment in the file
* MNextMasterLight.sol.
*/
import './MNextDataModel.sol';
contract MNextMaster is MNextDataModel{
/*
* ###########
* # STRUCTS #
* ###########
*/
// ////////
// / BANK /
// ////////
struct BankWrapper {
Bank bank;
bool isLocked;
}
// /////////
// / CHECK /
// /////////
struct CheckWrapper {
Check check;
bool isLocked;
}
// ////////
// / USER /
// ////////
struct User {
uint8 state;
bool isLocked;
}
// //////////////
// / UTXO (BTC) /
// //////////////
struct BTCutxo {
address utxo;
uint256 satoshi;
uint16 bank;
uint256 account;
}
/*
* ####################
* # PUBLIC VARIABLES #
* ####################
*/
//////////////////////////////
// SYSTEM'S KEY DESCRIPTORS //
//////////////////////////////
string public name;
string public token;
string public symbol;
string public admin;
string public api;
string public site;
string public explorer;
mapping (uint8 => NoteType) public noteTypes;
/*
* #####################
* # PRIVATE VARIABLES #
* #####################
*/
/////////////////////////////
// SYSTEM'S KEY CONTAINERS //
/////////////////////////////
mapping (uint16 => BankWrapper) private _banks;
mapping (uint256 => CheckWrapper) private _checks;
mapping (uint256 => Coin) private _coins;
mapping (uint256 => Note) private _notes;
mapping (address => User) private _users;
mapping (uint256 => BTCutxo) private _utxos;
/////////////////////////////
// SYSTEM'S KEY CONDITIONS //
/////////////////////////////
uint256 private _satoshiBase;
int32 private _reserveRatio;
uint16 private _multiplier;
/////////////////////////
// MAINTENANCE HELPERS //
/////////////////////////
uint16 private _nextBankId;
uint256 private _nextCoinId;
uint256 private _nextNoteId;
uint256 private _nextCheckId;
uint256 private _utxoPointer;
////////////////////////////////
// SYSTEM ADMIN'S CREDENTIALS //
////////////////////////////////
address payable private _rootUser;
bytes32 private _rootKey;
/*
* Contract constructor
* --------------------
* Construct the contract
*
* @param string memory sentence
* A sentence to protect master access.
* @param uint256 satoshiBase_
* Value to set as system's base unit.
* @param int32 reserveRatio_
* Value to set as system's reserve ratio.
* @param uint16 multiplier_
* Value to set as system's multiplier.
*/
constructor(string memory sentence, uint256 satoshiBase_,
int32 reserveRatio_, uint16 multiplier_) payable {
_rootUser = payable(msg.sender);
_rootKey = keccak256(abi.encodePacked(sentence));
_satoshiBase = satoshiBase_;
_reserveRatio = reserveRatio_;
_multiplier = multiplier_;
/*
* SETUP BTC GATEWAY.
*/
_nextBankId = 0;
_nextCheckId = 0;
_nextCoinId = 0;
_nextNoteId = 0;
}
// C A U T I O N ! ! !
//
// Don't forget to remove the section below in production to save the system
// tokens.
/*
* ##################
* # Mock functions #
* ##################
*/
/*
* Get mock coins
* --------------
* Create mock coins to the caller
*
* @param uint256 amount
* Amount of coins to create.
*/
function mockCreateCoins(uint256 amount) external {
_users[msg.sender].state = USER_ACTIVE_AND_RESTRICTIONLESS;
for (uint256 i=0; i<amount; i++) {
_coins[i] = Coin(address(0), i, 0, msg.sender, COIN_ACTIVE_AND_FREE);
_nextCoinId++;
}
}
/*
* Get mock coins
* --------------
* Create mock coins to a foreign user
*
* @param address user
* Address of the user to create mock coins for.
* @param uint256 amount
* Amount of coins to create.
*/
function mockCreateUserWithBalance(address user, uint256 amount) external {
_users[user].state = USER_ACTIVE_AND_RESTRICTIONLESS;
for (uint256 i=0; i<amount; i++) {
_coins[i] = Coin(address(0), i, 0, user, COIN_ACTIVE_AND_FREE);
_nextCoinId++;
}
}
/*
* Mock transaction between users
* ------------------------------
* Perform mock transaction between foreign users
*
* @param address sender
* Address of the user to send mock coins from.
* @param address target
* Address of the user to send mock coins to.
* @param uint256 amount
* Amount of coins to create.
*
* @note Please keep in mind, though it's a mock transaction function, it
* calls the real inside _transact() function. So sender must have
* enough coins to send. The function mockCreateCoins() is useful to
* help you out.
*/
function mockTransact(address sender, address target, uint256 amount)
external returns (bool) {
return _transact(sender, target, amount);
}
/*
* #########################
* # End of mock functions #
* #########################
*/
// Don't forget to remove the section above in production to save the system
// tokens.
//
// C A U T I O N ! ! !
/*
* ########################
* # System level actions #
* ########################
*/
/*
* Review coin supply
* ------------------
* Review the coin supply of the system
*/
function review() external {
_utxoPointer = 0;
for (uint16 i=0; i < _nextBankId; i++) __reviewBank(i);
__reviewCoins();
}
/*
* Set system admin name
* ---------------------
* Set the name of the system's admin
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newAdmin
* The new name of the admin.
*/
function setAdmin(string calldata sentence, string calldata newAdmin)
onlyAdmin(sentence) external {
admin = newAdmin;
}
/*
* Set system API root
* -------------------
* Set the link to the system's API root
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newApi
* The new link to the API root.
*/
function setApi(string calldata sentence, string calldata newApi)
onlyAdmin(sentence) external {
api = newApi;
}
/*
* Set system explorer
* -------------------
* Set the link to the system's data explorer
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newExplorer
* The new link to the explorer.
*/
function setExplorer(string calldata sentence, string calldata newExplorer)
onlyAdmin(sentence) external {
explorer = newExplorer;
}
/*
* Set multiplier
* --------------
* Set the value of the system's multiplier
*
* @param string calldata sentence
* A sentence to protect master access.
* @param uint16 newMultiplier_
* The new multiplier value.
*/
function setMultiplier(string calldata sentence, uint16 newMultiplier_)
onlyAdmin(sentence) external {
_multiplier = newMultiplier_;
this.review();
}
/*
* Set system name
* --------------
* Set the name of the system
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newName
* The new name of the system.
*/
function setName(string calldata sentence, string calldata newName)
onlyAdmin(sentence) external {
name = newName;
}
/*
* Set reserve ratio
* -----------------
* Set the value of the system's reserve ratio
*
* @param string calldata sentence
* A sentence to protect master access.
* @param int32 newReserveRatio_
* The new reserve ratio value.
*
* @note Since solidity doesn't handle fractions, to set the percentage
* value you have to multiply the original (fraction) value with 100.
*/
function setReserveRatio(string calldata sentence, int32 newReserveRatio_)
onlyAdmin(sentence) external {
_reserveRatio = newReserveRatio_;
this.review();
}
/*
* Set satoshi base
* ----------------
* Set the value of the system's Satoshi base
*
* @param string calldata sentence
* A sentence to protect master access.
* @param uint256 newSatoshiBase_
* The new Satoshi base value.
*/
function setSatoshiBase(string calldata sentence, uint256 newSatoshiBase_)
onlyAdmin(sentence) external {
_satoshiBase = newSatoshiBase_;
this.review();
}
/*
* Set system homepage
* -------------------
* Set the link to the system's homepage
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSite
* The new link to the homepage.
*/
function setSite(string calldata sentence, string calldata newSite)
onlyAdmin(sentence) external {
site = newSite;
}
/*
* Set token symbol
* ----------------
* Set the symbol of the system's token
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSymbol
* The new symbol of the token.
*/
function setSymbol(string calldata sentence, string calldata newSymbol)
onlyAdmin(sentence) external {
symbol = newSymbol;
}
/*
* Set token name
* --------------
* Set the name of the system's token
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newToken
* The new name of the token.
*/
function setToken(string calldata sentence, string calldata newToken)
onlyAdmin(sentence) external {
token = newToken;
}
/*
* ############################
* # System level information #
* ############################
*/
/*
* Get multiplier
* --------------
* Get the value of the system's multiplier
*
* @return uint16
* The actual multiplier value.
*/
function getMultiplier() external view returns (uint16) {
return _multiplier;
}
/*
* Get reserve ratio
* -----------------
* Get the value of the system's reserve ratio
*
* @return int32
* The actual reserve ratio value.
*
* @note Since solidity doesn't handle fractions, to receive the percentage
* value you have to divide the returned value with 100.
*/
function getReserveRatio() external view returns (int32) {
return _reserveRatio;
}
/*
* Get satoshi base
* ----------------
* Get the value of the system's Satoshi base
*
* @return uint256
* The actual Satoshi base value.
*/
function getSatoshiBase() external view returns (uint256) {
return _satoshiBase;
}
/*
* Get active coin count
* ---------------------
* Get the count of active coins in the system
*
* @return uint256
* The actual count of active coins.
*/
function getCoinCount() external view returns (uint256) {
uint256 result = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].state == COIN_ACTIVE_AND_FREE
|| _coins[i].state == COIN_ACTIVE_IN_CHECK
|| _coins[i].state == COIN_ACTIVE_IN_NOTE)
result++;
return result;
}
/*
* #########
* # Banks #
* #########
*/
////////////
// CREATE //
////////////
/*
* Create bank
* -----------
* Create (register) a bank
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata bankName
* The name of the bank to register.
* @param address mainAccount
* An address to be used as the bank's main account.
* @param string calldata firstPassPhrase
* A password phrase to be used as the first [0] security key.
*/
function createBank(string calldata sentence, string calldata bankName,
address mainAccount, string calldata firstPassPhrase)
onlyAdmin(sentence) lockBank(_nextBankId) external
returns (uint16) {
uint16 thisId = _nextBankId;
bytes32[] memory keyArray = new bytes32[] (1);
keyArray[0] = keccak256(abi.encodePacked(firstPassPhrase));
_banks[thisId].bank.name = bankName;
_banks[thisId].bank.api = '';
_banks[thisId].bank.site = '';
delete _banks[thisId].bank.accountsBTC;
_banks[thisId].bank.mainAccount = mainAccount;
delete _banks[thisId].bank.accounts;
delete _banks[thisId].bank.keys;
_banks[thisId].bank.state = BANK_CREATED;
_nextBankId++;
return thisId;
}
//////////
// READ //
//////////
/*
* Get a bank
* ----------
* Get data of a bank
*
* @param uint16 id
* ID of the check.
*
* @return Bank memory
* The data of the given bank.
*
* @note Keys of the bank rest hidden.
*/
function getBank(uint16 id) external view returns (Bank memory) {
bytes32[] memory keyArray = new bytes32[] (0);
Bank memory result = _banks[id].bank;
result.keys = keyArray;
return result;
}
/*
* Get bank count
* --------------
* Get the count of all banks.
*
* @return uin16
* The count of the banks.
*/
function getBankCount() external view returns (uint16) {
return _nextBankId;
}
/*
* Get all banks
* -------------
* Get data of all banks
*
* @return Bank[] memory
* List of data of all banks.
*
* @note Keys of banks rest hidden.
*/
function getBanks() external view returns (Bank[] memory) {
Bank[] memory result = new Bank[](_nextBankId);
bytes32[] memory keyArray = new bytes32[] (0);
for (uint16 i=0; i < _nextBankId; i++) {
result[i] = _banks[i].bank;
result[i].keys = keyArray;
}
return result;
}
////////////
// UPDATE //
////////////
/*
* TODO IMPLEMENT
*
* BTC accounts:
* - addBankBTCAccount(uint16 id, string calldata sentence, address btcAccount)
* - addBankBTCAccount(uint16 id, uint256 keyId, string calldata passPhrase, address btcAccount)
* - activateBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - activateBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - deleteBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - deleteBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - suspendBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - suspendBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
*
* Note: BTC account related functions autamotically call review()
*
* System accounts:
* - addBankAccount(uint16 id, string calldata sentence, address account)
* - addBankAccount(uint16 id, uint256 keyId, string calldata passPhrase, address account)
* - activateBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - activateBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - deleteBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - deleteBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - suspendBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - suspendBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
*
* - addBankKey(string calldata sentence, string calldata passPhrase)
* - addBankKey(uint256 keyId, string calldata passPhrase, string calldata passPhrase)
* - changeBankKey(uint16 id, uint256 affectedKeyId, string calldata sentence, string calldata newPassPhrase)
* - changeBankKey(uint16 id, uint256 affectedKeyId, uint256 keyId, string calldata passPhrase, string calldata newPassPhrase)
*
* TODO: CHANGE
*
* - More complex key validation system.
*/
/*
* Activate bank
* -------------
* Activate a non activated bank
*
* @param uint16 id
* The ID of the bank to activate.
* @param string calldata sentence
* A sentence to protect master access.
*/
function activateBank(uint16 id, string calldata sentence)
onlyAdmin(sentence) onlyExistingBank(id) lockBank(id)
external {
require(_banks[id].bank.state == BANK_CREATED,
'Cannot activate bank with a non appropriate state.');
_banks[id].bank.state = BANK_ACTIVE_AND_RESTRICTIONLESS;
}
/*
* Set API site link of a bank
* ---------------------------
* Set the link to the API root of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newApi
* The new API site link to set.
*/
function setBankApi(uint16 id, string calldata sentence,
string calldata newApi) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.api = newApi;
}
/*
* Set API site link of a bank
* ---------------------------
* Set the link to the API root of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newApi
* The new API site link to set.
*/
function setBankApi(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newApi) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.api = newApi;
}
/*
* Set name of a bank
* ------------------
* Set the name of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newName
* The new name to set.
*/
function setBankName(uint16 id, string calldata sentence,
string calldata newName) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.name = newName;
}
/*
* Set name of a bank
* ------------------
* Set the name of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newName
* The new name to set.
*/
function setBankName(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newName) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.name = newName;
}
/*
* Set homepage link of a bank
* ---------------------------
* Set the link to the homepage of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSite
* The new homepage link to set.
*/
function setBankSite(uint16 id, string calldata sentence,
string calldata newSite) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.site = newSite;
}
/*
* Set homepage link of a bank
* ---------------------------
* Set the link to the homepage of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newSite
* The new homepage link to set.
*/
function setBankSite(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newSite) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.site = newSite;
}
/*
* Suspend bank
* ------------
* Suspend am active bank
*
* @param uint16 id
* The ID of the bank to suspend.
* @param string calldata sentence
* A sentence to protect master access.
*/
function suspendBank(uint16 id, string calldata sentence)
onlyAdmin(sentence) onlyExistingBank(id) lockBank(id)
external {
require(_banks[id].bank.state == BANK_SUSPENDED
|| _banks[id].bank.state == BANK_DELETED,
'Cannot suspend a bank with a non appropriate state.');
_banks[id].bank.state = BANK_SUSPENDED;
}
////////////
// DELETE //
////////////
/*
* Delete bank
* -----------
* Delete an existing bank
*
* @param uint16 id
* The ID of the bank to delete.
* @param string calldata sentence
* A sentence to protect master access.
*/
function deleteBank(uint16 id, string calldata sentence) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
require(_banks[id].bank.state == BANK_DELETED,
'Cannot delete an already deleted bank.');
_banks[id].bank.state = BANK_DELETED;
}
/*
* ##########
* # Checks #
* ##########
*/
////////////
// CREATE //
////////////
/*
* Create check
* ------------
* Create a check without activation
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function createActiveCheck(uint256 amount, string calldata passPhrase)
lockUser(msg.sender) external returns (uint256) {
return _createCheck(amount, passPhrase, CHECK_ACTIVATED);
}
/*
* Create check
* ------------
* Create a check with activation
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function createCheck(uint256 amount, string calldata passPhrase)
lockUser(msg.sender) external returns (uint256) {
return _createCheck(amount, passPhrase, CHECK_CREATED);
}
//////////
// READ //
//////////
/*
* Get a check
* -----------
* Get data of a check
*
* @param uint256 id
* ID of the check.
*
* @note Check's key is hIdden. This way the key of the check cannot be
* retrieved. This design decision pushes big responsibility to the
* end-users' application.
*/
function getCheck(uint256 id) external view returns (Check memory) {
return Check(_checks[id].check.owner, _checks[id].check.coins,
'', _checks[id].check.state);
}
/*
* Get check value
* ---------------
* Get the value of a check
*
* @param uint256 id
* ID of the check.
*
* @return uint256
* The value of the given check.
*/
function getCheckValue(uint256 id) external view returns (uint256) {
return _checks[id].check.coins.length;
}
////////////
// UPDATE //
////////////
/*
* Activate check
* --------------
* Activate a non activated check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function activateCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require(_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_SUSPENDED,
'Cannot activate a check from a non appropriate state.');
_checks[id].check.state = CHECK_ACTIVATED;
}
/*
* Clear check
* -----------
* Clear an active check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function clearCeck(uint256 id, address from, string calldata passPhrase)
lockUser(msg.sender) lockUser(from)
lockCheck(id) onlyValIdCheckAction(id, from, passPhrase)
external {
require(_checks[id].check.state == CHECK_ACTIVATED,
'Cannot clear a non active check.');
require(_checks[id].check.owner == from,
'Original owner is needed to clear check.');
require(_checks[id].check.key == keccak256(abi.encodePacked(passPhrase)),
'Cannot clear a not opened check.');
// Note: consider to do this after the for loop. It is a hard decision.
_checks[id].check.state = CHECK_SPENT;
// There's no lack of {}s in the for loop and if selector below. :-)
for (uint256 i=0; i < _checks[id].check.coins.length; i++)
if (_coins[_checks[id].check.coins[i]].owner != from
|| _coins[_checks[id].check.coins[i]].state != COIN_ACTIVE_IN_CHECK)
revert('Internal error: Check clearance refused, safety first.');
else _coins[_checks[id].check.coins[i]].owner = msg.sender;
}
/*
* Suspend check
* -------------
* Suspend an existing and non suspended check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function suspendCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require((_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_ACTIVATED),
'Cannot perform suspending on check with non appropriate state.');
_checks[id].check.state = CHECK_SUSPENDED;
}
////////////
// DELETE //
////////////
/*
* Delete a check
* --------------
* Delete a not yet cleared check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function deleteCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require((_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_ACTIVATED
|| _checks[id].check.state == CHECK_SUSPENDED),
'Cannot perform deletioon on check with non appropriate state.');
// There's no lack of {} in the for loop below. :-)
for (uint i=0; i < _checks[id].check.coins.length; i++)
_coins[_checks[id].check.coins[i]].state = COIN_ACTIVE_AND_FREE;
_checks[id].check.state = CHECK_DELETED;
}
/*
* #########
* # Notes #
* #########
*/
// TODO: IMPLEMENT
/*
* ##############
* # Note types #
* ##############
*/
// TODO: IMPLEMENT
/*
* ###############################
* # User balance and user coins #
* ###############################
*/
/*
* Get the balance of a user
* -------------------------
* Get the total balance of a user
*
* @param address owner
* The address of the user to get balance for.
*
* @return uint256
* The balance of the user.
*/
function getBalance(address owner) external view returns (uint256) {
uint256 result = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) result += 1;
return result;
}
/*
* Get the coins of a user
* -----------------------
* Get the list of all coins of a user
*
* @param address owner
* The address of the user to get coins for.
*
* @return uint256[]
* List if IDs of the coins of the user.
*/
function getCoins(address owner) external view returns (uint256[] memory) {
// Becuse .push() is not available on memory arrays, a non-gas-friendly
// workaround should be used.
uint256 counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) counter++;
uint256[] memory result = new uint256[](counter);
counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) {
result[counter] = i;
counter++;
}
return result;
}
/*
* ################
* # TRANSACTIONS #
* ################
*/
/*
* Transact between users
* ----------------------
* Perform transaction between users
*
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextUser contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the user's contract depending on the implementation.
*/
function transact(address target, uint256 amount) lockUser(msg.sender)
lockUser(target) external returns (bool) {
return _transact(msg.sender, target, amount);
}
/*
* Transact between banks
* ----------------------
* Perform transaction between banks
*
* @param uint16 id
* ID of a bank to transact from.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param uint16 target
* ID of a bank to transact to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextBank contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the bank's contract depending on the implementation.
*/
function transactBankToBank(uint16 id, uint256 keyId,
string calldata passPhrase, uint16 target,
uint256 amount) onlyExistingBank(id)
lockBank(id)
onlyValIdBankAction(id, keyId, passPhrase)
onlyExistingBank(target) lockBank(target)
external returns (bool) {
return _transact(_banks[id].bank.mainAccount,
_banks[target].bank.mainAccount, amount);
}
/*
* Transact from bank to user
* --------------------------
* Perform transaction from a bank to a user
*
* @param uint16 id
* ID of a bank to transact from.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextBank contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the bank's contract depending on the implementation.
*/
function transactBankToUser(uint16 id, uint256 keyId,
string calldata passPhrase, address target,
uint256 amount) onlyExistingBank(id)
lockBank(id)
onlyValIdBankAction(id, keyId, passPhrase)
onlyExistingUser(target) lockUser(target)
external returns (bool) {
return _transact(_banks[id].bank.mainAccount, target, amount);
}
/*
* Transact from user to bank
* --------------------------
* Perform transaction from a user to a bank
*
* @param uint16 target
* ID of a bank to transact to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextUser contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the user's contract depending on the implementation.
*/
function transactUserToBank(uint16 target, uint256 amount)
lockUser(msg.sender) lockBank(target)
external returns (bool) {
return _transact(msg.sender, _banks[target].bank.mainAccount, amount);
}
// TODO: IMPLEMENT if bank want to use other than mainAccount both for
// bank->bank, bank->user and user->bank transactions.
/*
* ######################
* # INTERNAL FUNCTIONS #
* ######################
*/
/*
* Create check with state
* -----------------------
* Create a check with the given state
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
* @param uint8 state
* The state to create check with.
*/
function _createCheck(uint256 amount, string calldata passPhrase,
uint8 state) lockCheck(_nextCheckId)
private returns (uint256) {
// Becuse .push() is not available on memory arrays, a non-gas-friendly
// workaround should be used.
uint256 counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == msg.sender
&& _coins[i].state == COIN_ACTIVE_AND_FREE)
counter++;
require(counter >= amount,
'Not enough balance to create chekk.');
uint256[] memory coins = new uint256[](counter);
counter = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == msg.sender
&& _coins[i].state == COIN_ACTIVE_AND_FREE) {
_coins[i].state = COIN_ACTIVE_IN_CHECK;
coins[counter] = i;
counter++;
if (counter > amount) break;
}
uint256 _thisId = _nextCheckId;
if (_checks[_thisId].isLocked)
revert('Internal error: Check creation refused, safety first.');
_checks[_thisId].check = Check(msg.sender, coins,
keccak256(abi.encodePacked(passPhrase)),
state);
_nextCheckId++;
return _thisId;
}
/*
* Transact
* --------
* Perform transaction between addresses
*
* @param address owner
* Target address to send coins from.
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*/
function _transact(address owner, address target, uint256 amount)
internal returns (bool) {
bool result = false;
uint256[] memory coinSupply = new uint256[] (amount);
uint256 counter = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner
&& _coins[i].state == COIN_ACTIVE_AND_FREE) {
coinSupply[counter] = i;
counter++;
if (counter == amount) {
result = true;
break;
}
}
if (result) {
for (uint256 i=0; i < coinSupply.length; i++)
_coins[i].owner = target;
}
return result;
}
/*
* #####################
* # PRIVATE FUNCTIONS #
* #####################
*/
/*
* Review utxo deposits of a bank
* ------------------------------
* Collects information about presenting utxo deposits of the given bank
*
* @param uint16 id
* The ID of the bank to review.
*/
function __reviewBank(uint16 id) onlyExistingBank(id) lockBank(id) private {
for (uint256 i=0; i<_banks[id].bank.accountsBTC.length; i++) {
/*
* ACCES BTC GATEWAY.
*/
uint256 responseLength = 0;
address[] memory utxoList = new address[] (responseLength);
uint256[] memory amountList = new uint256[] (responseLength);
require(utxoList.length == amountList.length, 'BTC gateway error.');
for (uint256 j=0; j < utxoList.length; j++) {
_utxos[_utxoPointer] = BTCutxo(utxoList[j], amountList[j], id, i);
_utxoPointer++;
}
}
}
/*
* Review all the system coins
* ---------------------------
* Review system coins whether hey have the needed BTC deposits or not
*/
function __reviewCoins() private {
// HOW IT WORKS?
// 1. Gets all available utxos
// 2. Loops over coins and marks missing utxos
// 3. If there are coins without deposits, attempts to swap or delete them
// 4. If there are utxos without coins, they might used to coin swap
// 5. If there are utxos withoot coins after swaps, attempts to create coins
// 6. If something important happen in this functions events are mitted
}
/*
* #############
* # MODIFIERS #
* #############
*/
/*
* Lock a bank
* -----------
* Attempt to lock a bank during its data gets changed
*
* @param uint16 id
* The ID of the bank to lock.
*/
modifier lockBank(uint16 id) {
require(!_banks[id].isLocked,
'Cannot perform action on a locked bank.');
_banks[id].isLocked = true;
_;
_banks[id].isLocked = false;
}
/*
* Lock a check
* ------------
* Attempt to lock a check during its data gets changed
*
* @param uint256 id
* The ID of the check to lock.
*/
modifier lockCheck(uint256 id) {
require(!_checks[id].isLocked,
'Cannot perform action on a locked check.');
_checks[id].isLocked = true;
_;
_checks[id].isLocked = false;
}
/*
* Lock a user
* -----------
* Attempt to lock a user during its data gets changed
*
* @param address wallet
* The wallet of the user to lock.
*/
modifier lockUser(address wallet) {
require(!_users[wallet].isLocked,
'Cannot perform action on a locked user.');
_users[wallet].isLocked = true;
_;
_users[wallet].isLocked = false;
}
/*
* ValIdate admin
* --------------
* ValIdate access of the master contract owner
*
* @param string memory sentence
* A sentence to protect master access.
*/
modifier onlyAdmin(string memory sentence) {
require(msg.sender == _rootUser,
'Only admin can perform the action.');
require(keccak256(abi.encodePacked(sentence)) == _rootKey,
'Authorization failed.');
_;
}
/*
* Check existence of a bank
* -------------------------
* Check whether a bank exists or not
*
* @param uint16 id
* The ID of the bank to check.
*/
modifier onlyExistingBank(uint16 id) {
require(_banks[id].bank.state != STATE_UNAVAILABLE,
'Bank id must exist.');
_;
}
/*
* Check existence of a check
* --------------------------
* Check whether a check exists or not
*
* @param uint256 id
* The ID of the check to check.
*/
modifier onlyExistingCheck(uint256 id) {
require(_checks[id].check.state != STATE_UNAVAILABLE,
'Check id must exist.');
_;
}
/*
* Check existence of a coin
* -------------------------
* Check whether a coin exists or not
*
* @param uint256 id
* The ID of the coin to check.
*/
modifier onlyExistingCoin(uint256 id) {
require(_coins[id].state != STATE_UNAVAILABLE,
'Coin id must exist.');
_;
}
/*
* Check existence of a note
* -------------------------
* Check whether a note exists or not
*
* @param uint256 id
* The ID of the note to check.
*/
modifier onlyExistingNote(uint256 id) {
require(_notes[id].state != STATE_UNAVAILABLE,
'Note id must exist.');
_;
}
/*
* Check existence of a user
* -------------------------
* Check whether a user exists locally or not
*
* @param address who
* The address of the user to check.
*/
modifier onlyExistingUser(address who) {
require(_users[who].state != STATE_UNAVAILABLE
&& _users[who].state != USER_DELETED,
'User must exist.');
_;
}
modifier onlyValIdBankAction(uint16 id, uint256 keyId,
string calldata passPhrase) {
require(_banks[id].bank.keys.length < keyId,
'Cannot valIdate a non existing key.');
require(_banks[id].bank.keys[keyId]
== keccak256(abi.encodePacked(passPhrase)),
'Authorization failed.');
_;
}
/*
* ValIdate check access
* ---------------------
* ValIdate access credentials to perform actions on a check
*
* @param uint256 id
* ID of the check.
* @param address owner
* The address of owner of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
modifier onlyValIdCheckAction(uint256 id, address owner,
string calldata passPhrase) {
require(_checks[id].check.owner == owner,
'Cannot perform action on a foreign check.');
require(_checks[id].check.key
== keccak256(abi.encodePacked(passPhrase)),
'Cannot perform action on a not opened check.');
_;
}
} | Transact -------- Perform transaction between addresses @param address owner Target address to send coins from. @param address target Target address to send coins to. @param uint256 amount Amount of coins to send. @return bool True if the transaction was successful, false if not./ | function _transact(address owner, address target, uint256 amount)
internal returns (bool) {
bool result = false;
uint256[] memory coinSupply = new uint256[] (amount);
uint256 counter = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner
&& _coins[i].state == COIN_ACTIVE_AND_FREE) {
coinSupply[counter] = i;
counter++;
if (counter == amount) {
result = true;
break;
}
}
if (result) {
for (uint256 i=0; i < coinSupply.length; i++)
_coins[i].owner = target;
}
return result;
}
| 2,507,124 | [
1,
1429,
621,
27093,
11217,
2492,
3086,
6138,
225,
1758,
3410,
3639,
5916,
1758,
358,
1366,
276,
9896,
628,
18,
225,
1758,
1018,
3639,
5916,
1758,
358,
1366,
276,
9896,
358,
18,
225,
2254,
5034,
3844,
3639,
16811,
434,
276,
9896,
358,
1366,
18,
327,
1426,
540,
1053,
309,
326,
2492,
1703,
6873,
16,
629,
309,
486,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
2338,
621,
12,
2867,
3410,
16,
1758,
1018,
16,
2254,
5034,
3844,
13,
203,
15604,
2713,
1135,
261,
6430,
13,
288,
203,
203,
3639,
1426,
563,
273,
629,
31,
203,
3639,
2254,
5034,
8526,
3778,
13170,
3088,
1283,
273,
394,
2254,
5034,
8526,
261,
8949,
1769,
203,
3639,
2254,
5034,
3895,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
33,
20,
31,
277,
411,
389,
4285,
27055,
548,
31,
277,
27245,
203,
5411,
309,
261,
67,
71,
9896,
63,
77,
8009,
8443,
422,
3410,
203,
7734,
597,
389,
71,
9896,
63,
77,
8009,
2019,
422,
385,
6266,
67,
13301,
67,
4307,
67,
28104,
13,
288,
203,
7734,
13170,
3088,
1283,
63,
7476,
65,
273,
277,
31,
203,
7734,
3895,
9904,
31,
203,
7734,
309,
261,
7476,
422,
3844,
13,
288,
203,
10792,
563,
273,
638,
31,
203,
10792,
898,
31,
203,
7734,
289,
203,
5411,
289,
203,
3639,
309,
261,
2088,
13,
288,
203,
5411,
364,
261,
11890,
5034,
277,
33,
20,
31,
277,
411,
13170,
3088,
1283,
18,
2469,
31,
277,
27245,
203,
7734,
389,
71,
9896,
63,
77,
8009,
8443,
273,
1018,
31,
203,
3639,
289,
203,
3639,
327,
563,
31,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/8453/0x25f8fA4917180FF308883e37Ea27CEaEB68c1f19/sources/contracts/bridge/router/LocalBridgeConfig.sol | @dev Updates the fee structure for an already known bridge token. Sanity checks for the provided fee values | function _setTokenFee(
address token,
uint256 bridgeFee,
uint256 minFee,
uint256 maxFee
) internal {
require(bridgeFee < FEE_DENOMINATOR, "bridgeFee >= 100%");
require(minFee <= maxFee, "minFee > maxFee");
fee[token] = FeeStructure(uint40(bridgeFee), uint104(minFee), uint112(maxFee));
}
| 11,554,544 | [
1,
5121,
326,
14036,
3695,
364,
392,
1818,
4846,
10105,
1147,
18,
23123,
4271,
364,
326,
2112,
14036,
924,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
542,
1345,
14667,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
10105,
14667,
16,
203,
3639,
2254,
5034,
1131,
14667,
16,
203,
3639,
2254,
5034,
943,
14667,
203,
565,
262,
2713,
288,
203,
3639,
2583,
12,
18337,
14667,
411,
478,
9383,
67,
13296,
1872,
706,
3575,
16,
315,
18337,
14667,
1545,
2130,
9,
8863,
203,
3639,
2583,
12,
1154,
14667,
1648,
943,
14667,
16,
315,
1154,
14667,
405,
943,
14667,
8863,
203,
3639,
14036,
63,
2316,
65,
273,
30174,
6999,
12,
11890,
7132,
12,
18337,
14667,
3631,
2254,
21869,
12,
1154,
14667,
3631,
2254,
17666,
12,
1896,
14667,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotes {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (governance/utils/Votes.sol)
pragma solidity ^0.8.0;
import "../../utils/Context.sol";
import "../../utils/Counters.sol";
import "../../utils/Checkpoints.sol";
import "../../utils/cryptography/draft-EIP712.sol";
import "./IVotes.sol";
/**
* @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be
* transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of
* "representative" that will pool delegated voting units from different accounts and can then use it to vote in
* decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to
* delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.
*
* This contract is often combined with a token contract such that voting units correspond to token units. For an
* example, see {ERC721Votes}.
*
* The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed
* at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the
* cost of this history tracking optional.
*
* When using this module the derived contract must implement {_getVotingUnits} (for example, make it return
* {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the
* previous example, it would be included in {ERC721-_beforeTokenTransfer}).
*
* _Available since v4.5._
*/
abstract contract Votes is IVotes, Context, EIP712 {
using Checkpoints for Checkpoints.History;
using Counters for Counters.Counter;
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegation;
mapping(address => Checkpoints.History) private _delegateCheckpoints;
Checkpoints.History private _totalCheckpoints;
mapping(address => Counters.Counter) private _nonces;
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) public view virtual override returns (uint256) {
return _delegateCheckpoints[account].latest();
}
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return _delegateCheckpoints[account].getAtBlock(blockNumber);
}
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "Votes: block not yet mined");
return _totalCheckpoints.getAtBlock(blockNumber);
}
/**
* @dev Returns the current total supply of votes.
*/
function _getTotalSupply() internal view virtual returns (uint256) {
return _totalCheckpoints.latest();
}
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegation[account];
}
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
address account = _msgSender();
_delegate(account, delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Delegate all of `account`'s voting units to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address account, address delegatee) internal virtual {
address oldDelegate = delegates(account);
_delegation[account] = delegatee;
emit DelegateChanged(account, oldDelegate, delegatee);
_moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
}
/**
* @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
* should be zero. Total supply of voting units will be adjusted with mints and burns.
*/
function _transferVotingUnits(
address from,
address to,
uint256 amount
) internal virtual {
if (from == address(0)) {
_totalCheckpoints.push(_add, amount);
}
if (to == address(0)) {
_totalCheckpoints.push(_subtract, amount);
}
_moveDelegateVotes(delegates(from), delegates(to), amount);
}
/**
* @dev Moves delegated votes from one delegate to another.
*/
function _moveDelegateVotes(
address from,
address to,
uint256 amount
) private {
if (from != to && amount > 0) {
if (from != address(0)) {
(uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount);
emit DelegateVotesChanged(from, oldValue, newValue);
}
if (to != address(0)) {
(uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount);
emit DelegateVotesChanged(to, oldValue, newValue);
}
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @dev Returns an address nonce.
*/
function nonces(address owner) public view virtual returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev Returns the contract's {EIP712} domain separator.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev Must return the voting units held by an account.
*/
function _getVotingUnits(address) internal virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (token/ERC721/extensions/draft-ERC721Votes.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../governance/utils/Votes.sol";
/**
* @dev Extension of ERC721 to support voting and delegation as implemented by {Votes}, where each individual NFT counts
* as 1 vote unit.
*
* Tokens do not count as votes until they are delegated, because votes must be tracked which incurs an additional cost
* on every transfer. Token holders can either delegate to a trusted representative who will decide how to make use of
* the votes in governance decisions, or they can delegate to themselves to be their own representative.
*
* _Available since v4.5._
*/
abstract contract ERC721Votes is ERC721, Votes {
/**
* @dev Adjusts votes when tokens are transferred.
*
* Emits a {Votes-DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
_transferVotingUnits(from, to, 1);
super._afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Returns the balance of `account`.
*/
function _getVotingUnits(address account) internal virtual override returns (uint256) {
return balanceOf(account);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Checkpoints.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SafeCast.sol";
/**
* @dev This library defines the `History` struct, for checkpointing values as they change at different points in
* time, and later looking up past values by block number. See {Votes} as an example.
*
* To create a history of checkpoints define a variable type `Checkpoints.History` in your contract, and store a new
* checkpoint for the current transaction block using the {push} function.
*
* _Available since v4.5._
*/
library Checkpoints {
struct Checkpoint {
uint32 _blockNumber;
uint224 _value;
}
struct History {
Checkpoint[] _checkpoints;
}
/**
* @dev Returns the value in the latest checkpoint, or zero if there are no checkpoints.
*/
function latest(History storage self) internal view returns (uint256) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : self._checkpoints[pos - 1]._value;
}
/**
* @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one
* before it is returned, or zero otherwise.
*/
function getAtBlock(History storage self, uint256 blockNumber) internal view returns (uint256) {
require(blockNumber < block.number, "Checkpoints: block not yet mined");
uint256 high = self._checkpoints.length;
uint256 low = 0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (self._checkpoints[mid]._blockNumber > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : self._checkpoints[high - 1]._value;
}
/**
* @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block.
*
* Returns previous value and new value.
*/
function push(History storage self, uint256 value) internal returns (uint256, uint256) {
uint256 pos = self._checkpoints.length;
uint256 old = latest(self);
if (pos > 0 && self._checkpoints[pos - 1]._blockNumber == block.number) {
self._checkpoints[pos - 1]._value = SafeCast.toUint224(value);
} else {
self._checkpoints.push(
Checkpoint({_blockNumber: SafeCast.toUint32(block.number), _value: SafeCast.toUint224(value)})
);
}
return (old, value);
}
/**
* @dev Pushes a value onto a History, by updating the latest value using binary operation `op`. The new value will
* be set to `op(latest, delta)`.
*
* Returns previous value and new value.
*/
function push(
History storage self,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) internal returns (uint256, uint256) {
return push(self, op(latest(self), delta));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/draft-ERC721Votes.sol';
import './abstract/JBOperatable.sol';
import './interfaces/IJBProjects.sol';
import './libraries/JBOperations.sol';
/**
@notice
Stores project ownership and metadata.
@dev
Projects are represented as ERC-721's.
@dev
Adheres to:
IJBProjects: General interface for the methods in this contract that interact with the blockchain's state according to the protocol's rules.
@dev
Inherits from:
JBOperatable: Includes convenience functionality for checking a message sender's permissions before executing certain transactions.
ERC721Votes: A checkpointable standard definition for non-fungible tokens (NFTs).
Ownable: Includes convenience functionality for checking a message sender's permissions before executing certain transactions.
*/
contract JBProjects is IJBProjects, JBOperatable, ERC721Votes, Ownable {
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/**
@notice
The number of projects that have been created using this contract.
@dev
The count is incremented with each new project created.
The resulting ERC-721 token ID for each project is the newly incremented count value.
*/
uint256 public override count = 0;
/**
@notice
The metadata for each project, which can be used across several domains.
_projectId The ID of the project to which the metadata belongs.
_domain The domain within which the metadata applies. Applications can use the domain namespace as they wish.
*/
mapping(uint256 => mapping(uint256 => string)) public override metadataContentOf;
/**
@notice
The contract resolving each project ID to its ERC721 URI.
*/
IJBTokenUriResolver public override tokenUriResolver;
//*********************************************************************//
// ------------------------- external views -------------------------- //
//*********************************************************************//
/**
@notice
Returns the URI where the ERC-721 standard JSON of a project is hosted.
@param _projectId The ID of the project to get a URI of.
@return The token URI to use for the provided `_projectId`.
*/
function tokenURI(uint256 _projectId) public view override returns (string memory) {
// If there's no resolver, there's no URI.
if (tokenUriResolver == IJBTokenUriResolver(address(0))) return '';
// Return the resolved URI.
return tokenUriResolver.getUri(_projectId);
}
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/**
@param _operatorStore A contract storing operator assignments.
*/
constructor(IJBOperatorStore _operatorStore)
ERC721('Juicebox Projects', 'JUICEBOX')
EIP712('Juicebox Projects', '1')
JBOperatable(_operatorStore)
// solhint-disable-next-line no-empty-blocks
{
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/**
@notice
Create a new project for the specified owner, which mints an NFT (ERC-721) into their wallet.
@dev
Anyone can create a project on an owner's behalf.
@param _owner The address that will be the owner of the project.
@param _metadata A struct containing metadata content about the project, and domain within which the metadata applies.
@return projectId The token ID of the newly created project.
*/
function createFor(address _owner, JBProjectMetadata calldata _metadata)
external
override
returns (uint256 projectId)
{
// Increment the count, which will be used as the ID.
projectId = ++count;
// Mint the project.
_safeMint(_owner, projectId);
// Set the metadata if one was provided.
if (bytes(_metadata.content).length > 0)
metadataContentOf[projectId][_metadata.domain] = _metadata.content;
emit Create(projectId, _owner, _metadata, msg.sender);
}
/**
@notice
Allows a project owner to set the project's metadata content for a particular domain namespace.
@dev
Only a project's owner or operator can set its metadata.
@dev
Applications can use the domain namespace as they wish.
@param _projectId The ID of the project who's metadata is being changed.
@param _metadata A struct containing metadata content, and domain within which the metadata applies.
*/
function setMetadataOf(uint256 _projectId, JBProjectMetadata calldata _metadata)
external
override
requirePermission(ownerOf(_projectId), _projectId, JBOperations.SET_METADATA)
{
// Set the project's new metadata content within the specified domain.
metadataContentOf[_projectId][_metadata.domain] = _metadata.content;
emit SetMetadata(_projectId, _metadata, msg.sender);
}
/**
@notice
Sets the address of the resolver used to retrieve the tokenURI of projects.
@param _newResolver The address of the new resolver.
*/
function setTokenUriResolver(IJBTokenUriResolver _newResolver) external override onlyOwner {
// Store the new resolver.
tokenUriResolver = _newResolver;
emit SetTokenUriResolver(_newResolver, msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBOperatable.sol';
//*********************************************************************//
// --------------------------- custom errors -------------------------- //
//*********************************************************************//
error UNAUTHORIZED();
/**
@notice
Modifiers to allow access to functions based on the message sender's operator status.
*/
abstract contract JBOperatable is IJBOperatable {
//*********************************************************************//
// ---------------------------- modifiers ---------------------------- //
//*********************************************************************//
modifier requirePermission(
address _account,
uint256 _domain,
uint256 _permissionIndex
) {
_requirePermission(_account, _domain, _permissionIndex);
_;
}
modifier requirePermissionAllowingOverride(
address _account,
uint256 _domain,
uint256 _permissionIndex,
bool _override
) {
_requirePermissionAllowingOverride(_account, _domain, _permissionIndex, _override);
_;
}
//*********************************************************************//
// ---------------- public immutable stored properties --------------- //
//*********************************************************************//
/**
@notice
A contract storing operator assignments.
*/
IJBOperatorStore public immutable override operatorStore;
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/**
@param _operatorStore A contract storing operator assignments.
*/
constructor(IJBOperatorStore _operatorStore) {
operatorStore = _operatorStore;
}
//*********************************************************************//
// -------------------------- internal views ------------------------- //
//*********************************************************************//
/**
@notice
Require the message sender is either the account or has the specified permission.
@param _account The account to allow.
@param _domain The domain within which the permission index will be checked.
@param _domain The permission index that an operator must have within the specified domain to be allowed.
*/
function _requirePermission(
address _account,
uint256 _domain,
uint256 _permissionIndex
) internal view {
if (
msg.sender != _account &&
!operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
!operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
) revert UNAUTHORIZED();
}
/**
@notice
Require the message sender is either the account, has the specified permission, or the override condition is true.
@param _account The account to allow.
@param _domain The domain within which the permission index will be checked.
@param _domain The permission index that an operator must have within the specified domain to be allowed.
@param _override The override condition to allow.
*/
function _requirePermissionAllowingOverride(
address _account,
uint256 _domain,
uint256 _permissionIndex,
bool _override
) internal view {
if (
!_override &&
msg.sender != _account &&
!operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
!operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
) revert UNAUTHORIZED();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
enum JBBallotState {
Active,
Approved,
Failed
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBFundingCycleData.sol';
import './../structs/JBFundingCycleMetadata.sol';
import './../structs/JBProjectMetadata.sol';
import './../structs/JBGroupedSplits.sol';
import './../structs/JBFundAccessConstraints.sol';
import './../structs/JBProjectMetadata.sol';
import './IJBDirectory.sol';
import './IJBToken.sol';
import './IJBPaymentTerminal.sol';
import './IJBFundingCycleStore.sol';
import './IJBTokenStore.sol';
import './IJBSplitsStore.sol';
interface IJBController {
event LaunchProject(uint256 configuration, uint256 projectId, string memo, address caller);
event LaunchFundingCycles(uint256 configuration, uint256 projectId, string memo, address caller);
event ReconfigureFundingCycles(
uint256 configuration,
uint256 projectId,
string memo,
address caller
);
event SetFundAccessConstraints(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
JBFundAccessConstraints constraints,
address caller
);
event DistributeReservedTokens(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address beneficiary,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
address caller
);
event DistributeToReservedTokenSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
uint256 tokenCount,
address caller
);
event MintTokens(
address indexed beneficiary,
uint256 indexed projectId,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
uint256 reservedRate,
address caller
);
event BurnTokens(
address indexed holder,
uint256 indexed projectId,
uint256 tokenCount,
string memo,
address caller
);
event Migrate(uint256 indexed projectId, IJBController to, address caller);
event PrepMigration(uint256 indexed projectId, IJBController from, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function tokenStore() external view returns (IJBTokenStore);
function splitsStore() external view returns (IJBSplitsStore);
function directory() external view returns (IJBDirectory);
function reservedTokenBalanceOf(uint256 _projectId, uint256 _reservedRate)
external
view
returns (uint256);
function distributionLimitOf(
uint256 _projectId,
uint256 _configuration,
IJBPaymentTerminal _terminal,
address _token
) external view returns (uint256 distributionLimit, uint256 distributionLimitCurrency);
function overflowAllowanceOf(
uint256 _projectId,
uint256 _configuration,
IJBPaymentTerminal _terminal,
address _token
) external view returns (uint256 overflowAllowance, uint256 overflowAllowanceCurrency);
function totalOutstandingTokensOf(uint256 _projectId, uint256 _reservedRate)
external
view
returns (uint256);
function currentFundingCycleOf(uint256 _projectId)
external
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function queuedFundingCycleOf(uint256 _projectId)
external
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function launchProjectFor(
address _owner,
JBProjectMetadata calldata _projectMetadata,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
IJBPaymentTerminal[] memory _terminals,
string calldata _memo
) external returns (uint256 projectId);
function launchFundingCyclesFor(
uint256 _projectId,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
IJBPaymentTerminal[] memory _terminals,
string calldata _memo
) external returns (uint256 configuration);
function reconfigureFundingCyclesOf(
uint256 _projectId,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
string calldata _memo
) external returns (uint256);
function issueTokenFor(
uint256 _projectId,
string calldata _name,
string calldata _symbol
) external returns (IJBToken token);
function changeTokenOf(
uint256 _projectId,
IJBToken _token,
address _newOwner
) external;
function mintTokensOf(
uint256 _projectId,
uint256 _tokenCount,
address _beneficiary,
string calldata _memo,
bool _preferClaimedTokens,
bool _useReservedRate
) external returns (uint256 beneficiaryTokenCount);
function burnTokensOf(
address _holder,
uint256 _projectId,
uint256 _tokenCount,
string calldata _memo,
bool _preferClaimedTokens
) external;
function distributeReservedTokensOf(uint256 _projectId, string memory _memo)
external
returns (uint256);
function prepForMigrationOf(uint256 _projectId, IJBController _from) external;
function migrate(uint256 _projectId, IJBController _to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBPaymentTerminal.sol';
import './IJBProjects.sol';
import './IJBFundingCycleStore.sol';
import './IJBController.sol';
interface IJBDirectory {
event SetController(uint256 indexed projectId, IJBController indexed controller, address caller);
event AddTerminal(uint256 indexed projectId, IJBPaymentTerminal indexed terminal, address caller);
event SetTerminals(uint256 indexed projectId, IJBPaymentTerminal[] terminals, address caller);
event SetPrimaryTerminal(
uint256 indexed projectId,
address indexed token,
IJBPaymentTerminal indexed terminal,
address caller
);
event SetIsAllowedToSetFirstController(address indexed addr, bool indexed flag, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function controllerOf(uint256 _projectId) external view returns (IJBController);
function isAllowedToSetFirstController(address _address) external view returns (bool);
function terminalsOf(uint256 _projectId) external view returns (IJBPaymentTerminal[] memory);
function isTerminalOf(uint256 _projectId, IJBPaymentTerminal _terminal)
external
view
returns (bool);
function primaryTerminalOf(uint256 _projectId, address _token)
external
view
returns (IJBPaymentTerminal);
function setControllerOf(uint256 _projectId, IJBController _controller) external;
function setTerminalsOf(uint256 _projectId, IJBPaymentTerminal[] calldata _terminals) external;
function setPrimaryTerminalOf(
uint256 _projectId,
address _token,
IJBPaymentTerminal _terminal
) external;
function setIsAllowedToSetFirstController(address _address, bool _flag) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './../enums/JBBallotState.sol';
interface IJBFundingCycleBallot {
function duration() external view returns (uint256);
function stateOf(
uint256 _projectId,
uint256 _configuration,
uint256 _start
) external view returns (JBBallotState);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './IJBPayDelegate.sol';
import './IJBRedemptionDelegate.sol';
import './../structs/JBPayParamsData.sol';
import './../structs/JBRedeemParamsData.sol';
interface IJBFundingCycleDataSource {
function payParams(JBPayParamsData calldata _data)
external
view
returns (
uint256 weight,
string memory memo,
IJBPayDelegate delegate
);
function redeemParams(JBRedeemParamsData calldata _data)
external
view
returns (
uint256 reclaimAmount,
string memory memo,
IJBRedemptionDelegate delegate
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleBallot.sol';
import './../enums/JBBallotState.sol';
import './../structs/JBFundingCycle.sol';
import './../structs/JBFundingCycleData.sol';
interface IJBFundingCycleStore {
event Configure(
uint256 indexed configuration,
uint256 indexed projectId,
JBFundingCycleData data,
uint256 metadata,
uint256 mustStartAtOrAfter,
address caller
);
event Init(uint256 indexed configuration, uint256 indexed projectId, uint256 indexed basedOn);
function latestConfigurationOf(uint256 _projectId) external view returns (uint256);
function get(uint256 _projectId, uint256 _configuration)
external
view
returns (JBFundingCycle memory);
function queuedOf(uint256 _projectId) external view returns (JBFundingCycle memory);
function currentOf(uint256 _projectId) external view returns (JBFundingCycle memory);
function currentBallotStateOf(uint256 _projectId) external view returns (JBBallotState);
function configureFor(
uint256 _projectId,
JBFundingCycleData calldata _data,
uint256 _metadata,
uint256 _mustStartAtOrAfter
) external returns (JBFundingCycle memory fundingCycle);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBOperatorStore.sol';
interface IJBOperatable {
function operatorStore() external view returns (IJBOperatorStore);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBOperatorData.sol';
interface IJBOperatorStore {
event SetOperator(
address indexed operator,
address indexed account,
uint256 indexed domain,
uint256[] permissionIndexes,
uint256 packed
);
function permissionsOf(
address _operator,
address _account,
uint256 _domain
) external view returns (uint256);
function hasPermission(
address _operator,
address _account,
uint256 _domain,
uint256 _permissionIndex
) external view returns (bool);
function hasPermissions(
address _operator,
address _account,
uint256 _domain,
uint256[] calldata _permissionIndexes
) external view returns (bool);
function setOperator(JBOperatorData calldata _operatorData) external;
function setOperators(JBOperatorData[] calldata _operatorData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBDidPayData.sol';
interface IJBPayDelegate {
function didPay(JBDidPayData calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBDirectory.sol';
interface IJBPaymentTerminal {
function acceptsToken(address _token) external view returns (bool);
function currencyForToken(address _token) external view returns (uint256);
function decimalsForToken(address _token) external view returns (uint256);
// Return value must be a fixed point number with 18 decimals.
function currentEthOverflowOf(uint256 _projectId) external view returns (uint256);
function pay(
uint256 _projectId,
uint256 _amount,
address _token,
address _beneficiary,
uint256 _minReturnedTokens,
bool _preferClaimedTokens,
string calldata _memo,
bytes calldata _metadata
) external payable returns (uint256 beneficiaryTokenCount);
function addToBalanceOf(
uint256 _projectId,
uint256 _amount,
address _token,
string calldata _memo
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import './IJBPaymentTerminal.sol';
import './IJBTokenUriResolver.sol';
import './../structs/JBProjectMetadata.sol';
import './IJBTokenUriResolver.sol';
interface IJBProjects is IERC721 {
event Create(
uint256 indexed projectId,
address indexed owner,
JBProjectMetadata metadata,
address caller
);
event SetMetadata(uint256 indexed projectId, JBProjectMetadata metadata, address caller);
event SetTokenUriResolver(IJBTokenUriResolver resolver, address caller);
function count() external view returns (uint256);
function metadataContentOf(uint256 _projectId, uint256 _domain)
external
view
returns (string memory);
function tokenUriResolver() external view returns (IJBTokenUriResolver);
function createFor(address _owner, JBProjectMetadata calldata _metadata)
external
returns (uint256 projectId);
function setMetadataOf(uint256 _projectId, JBProjectMetadata calldata _metadata) external;
function setTokenUriResolver(IJBTokenUriResolver _newResolver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './../structs/JBDidRedeemData.sol';
interface IJBRedemptionDelegate {
function didRedeem(JBDidRedeemData calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import '../structs/JBSplitAllocationData.sol';
interface IJBSplitAllocator {
function allocate(JBSplitAllocationData calldata _data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBOperatorStore.sol';
import './IJBProjects.sol';
import './IJBDirectory.sol';
import './IJBSplitAllocator.sol';
import './../structs/JBSplit.sol';
interface IJBSplitsStore {
event SetSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
address caller
);
function projects() external view returns (IJBProjects);
function directory() external view returns (IJBDirectory);
function splitsOf(
uint256 _projectId,
uint256 _domain,
uint256 _group
) external view returns (JBSplit[] memory);
function set(
uint256 _projectId,
uint256 _domain,
uint256 _group,
JBSplit[] memory _splits
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IJBToken {
function decimals() external view returns (uint8);
function totalSupply(uint256 _projectId) external view returns (uint256);
function balanceOf(address _account, uint256 _projectId) external view returns (uint256);
function mint(
uint256 _projectId,
address _account,
uint256 _amount
) external;
function burn(
uint256 _projectId,
address _account,
uint256 _amount
) external;
function approve(
uint256,
address _spender,
uint256 _amount
) external;
function transfer(
uint256 _projectId,
address _to,
uint256 _amount
) external;
function transferFrom(
uint256 _projectId,
address _from,
address _to,
uint256 _amount
) external;
function transferOwnership(address _newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBProjects.sol';
import './IJBToken.sol';
interface IJBTokenStore {
event Issue(
uint256 indexed projectId,
IJBToken indexed token,
string name,
string symbol,
address caller
);
event Mint(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
bool tokensWereClaimed,
bool preferClaimedTokens,
address caller
);
event Burn(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
uint256 initialUnclaimedBalance,
uint256 initialClaimedBalance,
bool preferClaimedTokens,
address caller
);
event Claim(
address indexed holder,
uint256 indexed projectId,
uint256 initialUnclaimedBalance,
uint256 amount,
address caller
);
event ShouldRequireClaim(uint256 indexed projectId, bool indexed flag, address caller);
event Change(
uint256 indexed projectId,
IJBToken indexed newToken,
IJBToken indexed oldToken,
address owner,
address caller
);
event Transfer(
address indexed holder,
uint256 indexed projectId,
address indexed recipient,
uint256 amount,
address caller
);
function tokenOf(uint256 _projectId) external view returns (IJBToken);
function projectOf(IJBToken _token) external view returns (uint256);
function projects() external view returns (IJBProjects);
function unclaimedBalanceOf(address _holder, uint256 _projectId) external view returns (uint256);
function unclaimedTotalSupplyOf(uint256 _projectId) external view returns (uint256);
function totalSupplyOf(uint256 _projectId) external view returns (uint256);
function balanceOf(address _holder, uint256 _projectId) external view returns (uint256 _result);
function requireClaimFor(uint256 _projectId) external view returns (bool);
function issueFor(
uint256 _projectId,
string calldata _name,
string calldata _symbol
) external returns (IJBToken token);
function changeFor(
uint256 _projectId,
IJBToken _token,
address _newOwner
) external returns (IJBToken oldToken);
function burnFrom(
address _holder,
uint256 _projectId,
uint256 _amount,
bool _preferClaimedTokens
) external;
function mintFor(
address _holder,
uint256 _projectId,
uint256 _amount,
bool _preferClaimedTokens
) external;
function shouldRequireClaimingFor(uint256 _projectId, bool _flag) external;
function claimFor(
address _holder,
uint256 _projectId,
uint256 _amount
) external;
function transferFrom(
address _holder,
uint256 _projectId,
address _recipient,
uint256 _amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IJBTokenUriResolver {
function getUri(uint256 _projectId) external view returns (string memory tokenUri);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
library JBOperations {
uint256 public constant RECONFIGURE = 1;
uint256 public constant REDEEM = 2;
uint256 public constant MIGRATE_CONTROLLER = 3;
uint256 public constant MIGRATE_TERMINAL = 4;
uint256 public constant PROCESS_FEES = 5;
uint256 public constant SET_METADATA = 6;
uint256 public constant ISSUE = 7;
uint256 public constant CHANGE_TOKEN = 8;
uint256 public constant MINT = 9;
uint256 public constant BURN = 10;
uint256 public constant CLAIM = 11;
uint256 public constant TRANSFER = 12;
uint256 public constant REQUIRE_CLAIM = 13;
uint256 public constant SET_CONTROLLER = 14;
uint256 public constant SET_TERMINALS = 15;
uint256 public constant SET_PRIMARY_TERMINAL = 16;
uint256 public constant USE_ALLOWANCE = 17;
uint256 public constant SET_SPLITS = 18;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
library JBSplitsGroups {
uint256 public constant ETH_PAYOUT = 1;
uint256 public constant RESERVED_TOKENS = 2;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBTokenAmount.sol';
struct JBDidPayData {
// The address from which the payment originated.
address payer;
// The ID of the project for which the payment was made.
uint256 projectId;
// The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount amount;
// The number of project tokens minted for the beneficiary.
uint256 projectTokenCount;
// The address to which the tokens were minted.
address beneficiary;
// The memo that is being emitted alongside the payment.
string memo;
// Metadata to send to the delegate.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBTokenAmount.sol';
struct JBDidRedeemData {
// The holder of the tokens being redeemed.
address holder;
// The project to which the redeemed tokens are associated.
uint256 projectId;
// The number of project tokens being redeemed.
uint256 projectTokenCount;
// The reclaimed amount. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount reclaimedAmount;
// The address to which the reclaimed amount will be sent.
address payable beneficiary;
// The memo that is being emitted alongside the redemption.
string memo;
// Metadata to send to the delegate.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
struct JBFundAccessConstraints {
// The terminal within which the distribution limit and the overflow allowance applies.
IJBPaymentTerminal terminal;
// The token for which the fund access constraints apply.
address token;
// The amount of the distribution limit, as a fixed point number with the same number of decimals as the terminal within which the limit applies.
uint256 distributionLimit;
// The currency of the distribution limit.
uint256 distributionLimitCurrency;
// The amount of the allowance, as a fixed point number with the same number of decimals as the terminal within which the allowance applies.
uint256 overflowAllowance;
// The currency of the overflow allowance.
uint256 overflowAllowanceCurrency;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleBallot.sol';
struct JBFundingCycle {
// The funding cycle number for each project.
// Each funding cycle has a number that is an increment of the cycle that directly preceded it.
// Each project's first funding cycle has a number of 1.
uint256 number;
// The timestamp when the parameters for this funding cycle were configured.
// This value will stay the same for subsequent funding cycles that roll over from an originally configured cycle.
uint256 configuration;
// The `configuration` of the funding cycle that was active when this cycle was created.
uint256 basedOn;
// The timestamp marking the moment from which the funding cycle is considered active.
// It is a unix timestamp measured in seconds.
uint256 start;
// The number of seconds the funding cycle lasts for, after which a new funding cycle will start.
// A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties.
// If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle.
// If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
uint256 duration;
// A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on.
// For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
uint256 weight;
// A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`.
// If it's 0, each funding cycle will have equal weight.
// If the number is 90%, the next funding cycle will have a 10% smaller weight.
// This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
uint256 discountRate;
// An address of a contract that says whether a proposed reconfiguration should be accepted or rejected.
// It can be used to create rules around how a project owner can change funding cycle parameters over time.
IJBFundingCycleBallot ballot;
// Extra data that can be associated with a funding cycle.
uint256 metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleBallot.sol';
struct JBFundingCycleData {
// The number of seconds the funding cycle lasts for, after which a new funding cycle will start.
// A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties.
// If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle.
// If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
uint256 duration;
// A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on.
// For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
uint256 weight;
// A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`.
// If it's 0, each funding cycle will have equal weight.
// If the number is 90%, the next funding cycle will have a 10% smaller weight.
// This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
uint256 discountRate;
// An address of a contract that says whether a proposed reconfiguration should be accepted or rejected.
// It can be used to create rules around how a project owner can change funding cycle parameters over time.
IJBFundingCycleBallot ballot;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleDataSource.sol';
struct JBFundingCycleMetadata {
// The reserved rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_RESERVED_RATE`.
uint256 reservedRate;
// The redemption rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
uint256 redemptionRate;
// The redemption rate to use during an active ballot of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
uint256 ballotRedemptionRate;
// If the pay functionality should be paused during the funding cycle.
bool pausePay;
// If the distribute functionality should be paused during the funding cycle.
bool pauseDistributions;
// If the redeem functionality should be paused during the funding cycle.
bool pauseRedeem;
// If the burn functionality should be paused during the funding cycle.
bool pauseBurn;
// If the mint functionality should be allowed during the funding cycle.
bool allowMinting;
// If changing tokens should be allowed during this funding cycle.
bool allowChangeToken;
// If migrating terminals should be allowed during this funding cycle.
bool allowTerminalMigration;
// If migrating controllers should be allowed during this funding cycle.
bool allowControllerMigration;
// If setting terminals should be allowed during this funding cycle.
bool allowSetTerminals;
// If setting a new controller should be allowed during this funding cycle.
bool allowSetController;
// If fees should be held during this funding cycle.
bool holdFees;
// If redemptions should use the project's balance held in all terminals instead of the project's local terminal balance from which the redemption is being fulfilled.
bool useTotalOverflowForRedemptions;
// If the data source should be used for pay transactions during this funding cycle.
bool useDataSourceForPay;
// If the data source should be used for redeem transactions during this funding cycle.
bool useDataSourceForRedeem;
// The data source to use during this funding cycle.
IJBFundingCycleDataSource dataSource;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBSplit.sol';
import '../libraries/JBSplitsGroups.sol';
struct JBGroupedSplits {
// The group indentifier.
uint256 group;
// The splits to associate with the group.
JBSplit[] splits;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBOperatorData {
// The address of the operator.
address operator;
// The domain within which the operator is being given permissions.
// A domain of 0 is a wildcard domain, which gives an operator access to all domains.
uint256 domain;
// The indexes of the permissions the operator is being given.
uint256[] permissionIndexes;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
import './JBTokenAmount.sol';
struct JBPayParamsData {
// The terminal that is facilitating the payment.
IJBPaymentTerminal terminal;
// The address from which the payment originated.
address payer;
// The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount amount;
// The ID of the project being paid.
uint256 projectId;
// The weight of the funding cycle during which the payment is being made.
uint256 weight;
// The reserved rate of the funding cycle during which the payment is being made.
uint256 reservedRate;
// The memo that was sent alongside the payment.
string memo;
// Arbitrary metadata provided by the payer.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBProjectMetadata {
// Metadata content.
string content;
// The domain within which the metadata applies.
uint256 domain;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
struct JBRedeemParamsData {
// The terminal that is facilitating the redemption.
IJBPaymentTerminal terminal;
// The holder of the tokens being redeemed.
address holder;
// The ID of the project whos tokens are being redeemed.
uint256 projectId;
// The proposed number of tokens being redeemed, as a fixed point number with 18 decimals.
uint256 tokenCount;
// The total supply of tokens used in the calculation, as a fixed point number with 18 decimals.
uint256 totalSupply;
// The amount of overflow used in the reclaim amount calculation.
uint256 overflow;
// The number of decimals included in the reclaim amount fixed point number.
uint256 decimals;
// The currency that the reclaim amount is expected to be in terms of.
uint256 currency;
// The amount that should be reclaimed by the redeemer using the protocol's standard bonding curve redemption formula.
uint256 reclaimAmount;
// If overflow across all of a project's terminals is being used when making redemptions.
bool useTotalOverflow;
// The redemption rate of the funding cycle during which the redemption is being made.
uint256 redemptionRate;
// The ballot redemption rate of the funding cycle during which the redemption is being made.
uint256 ballotRedemptionRate;
// The proposed memo that is being emitted alongside the redemption.
string memo;
// Arbitrary metadata provided by the redeemer.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBSplitAllocator.sol';
struct JBSplit {
// A flag that only has effect if a projectId is also specified, and the project has a token contract attached.
// If so, this flag indicates if the tokens that result from making a payment to the project should be delivered claimed into the beneficiary's wallet, or unclaimed to save gas.
bool preferClaimed;
// A flag indicating if a distribution to a project should prefer triggering it's addToBalance function instead of its pay function.
bool preferAddToBalance;
// The percent of the whole group that this split occupies. This number is out of `JBConstants.SPLITS_TOTAL_PERCENT`.
uint256 percent;
// If an allocator is not set but a projectId is set, funds will be sent to the protocol treasury belonging to the project who's ID is specified.
// Resulting tokens will be routed to the beneficiary with the claimed token preference respected.
uint256 projectId;
// The role the of the beneficary depends on whether or not projectId is specified, and whether or not an allocator is specified.
// If allocator is set, the beneficiary will be forwarded to the allocator for it to use.
// If allocator is not set but projectId is set, the beneficiary is the address to which the project's tokens will be sent that result from a payment to it.
// If neither allocator or projectId are set, the beneficiary is where the funds from the split will be sent.
address payable beneficiary;
// Specifies if the split should be unchangeable until the specified time, with the exception of extending the locked period.
uint256 lockedUntil;
// If an allocator is specified, funds will be sent to the allocator contract along with all properties of this split.
IJBSplitAllocator allocator;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBSplit.sol';
import './JBTokenAmount.sol';
struct JBSplitAllocationData {
// The token being sent to the split allocator.
address token;
// The amount being sent to the split allocator, as a fixed point number.
uint256 amount;
// The number of decimals in the amount.
uint256 decimals;
// The project to which the split belongs.
uint256 projectId;
// The group to which the split belongs.
uint256 group;
// The split that caused the allocation.
JBSplit split;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBTokenAmount {
// The token the payment was made in.
address token;
// The amount of tokens that was paid, as a fixed point number.
uint256 value;
// The number of decimals included in the value fixed point number.
uint256 decimals;
// The expected currency of the value.
uint256 currency;
} | * @dev Returns the absolute unsigned value of a signed value./ must be unchecked in order to support `n = type(int256).min` | function abs(int256 n) internal pure returns (uint256) {
unchecked {
return uint256(n >= 0 ? n : -n);
}
}
| 634,907 | [
1,
1356,
326,
4967,
9088,
460,
434,
279,
6726,
460,
18,
19,
1297,
506,
22893,
316,
1353,
358,
2865,
1375,
82,
273,
618,
12,
474,
5034,
2934,
1154,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2417,
12,
474,
5034,
290,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
327,
2254,
5034,
12,
82,
1545,
374,
692,
290,
294,
300,
82,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/liquidators/EnglishAuctionCollateralLiquidator.sol | * @title English Auction Collateral Liquidator @author MetaStreet Labs/ | contract EnglishAuctionCollateralLiquidator is ICollateralLiquidator, ReentrancyGuard {
using SafeERC20 for IERC20;
string public constant IMPLEMENTATION_VERSION = "1.1";
uint256 internal constant BASIS_POINTS_SCALE = 10_000;
error InvalidParameters();
error InvalidToken();
error InvalidAuction();
error InvalidLiquidation();
error InvalidBid();
error InvalidClaim();
pragma solidity 0.8.20;
struct Auction {
bytes32 liquidationHash;
uint64 endTime;
address highestBidder;
uint256 highestBid;
}
struct Liquidation {
address source;
address currencyToken;
uint16 auctionCount;
bytes32 liquidationContextHash;
uint256 proceeds;
}
bytes32 indexed liquidationHash,
address indexed source,
bytes32 indexed liquidationContextHash,
address currencyToken,
uint16 auctionCount
);
bytes32 indexed liquidationHash,
address indexed collateralToken,
uint256 indexed collateralTokenId
);
bytes32 indexed liquidationHash,
address indexed collateralToken,
uint256 indexed collateralTokenId,
uint64 endTime
);
bytes32 indexed liquidationHash,
address indexed collateralToken,
uint256 indexed collateralTokenId,
uint64 endTime
);
bytes32 indexed liquidationHash,
address indexed collateralToken,
uint256 indexed collateralTokenId,
address bidder,
uint256 amount
);
bytes32 indexed liquidationHash,
address indexed collateralToken,
uint256 indexed collateralTokenId,
address winner,
uint256 proceeds
);
address internal immutable _collateralWrapper2;
address internal immutable _collateralWrapper3;
address internal immutable _collateralWrapper4;
address internal immutable _collateralWrapper5;
event LiquidationStarted(
event AuctionCreated(
event AuctionStarted(
event AuctionExtended(
event AuctionBid(
event AuctionEnded(
event LiquidationEnded(bytes32 indexed liquidationHash, uint256 proceeds);
bool private _initialized;
uint64 private _auctionDuration;
uint64 private _timeExtensionWindow;
uint64 private _timeExtension;
uint64 private _minimumBidBasisPoints;
address internal immutable _collateralWrapper1;
mapping(address => mapping(uint256 => Auction)) private _auctions;
mapping(bytes32 => Liquidation) private _liquidations;
constructor(address[] memory collateralWrappers_) {
if (collateralWrappers_.length > 5) revert InvalidParameters();
_collateralWrapper1 = (collateralWrappers_.length > 0) ? collateralWrappers_[0] : address(0);
_collateralWrapper2 = (collateralWrappers_.length > 1) ? collateralWrappers_[1] : address(0);
_collateralWrapper3 = (collateralWrappers_.length > 2) ? collateralWrappers_[2] : address(0);
_collateralWrapper4 = (collateralWrappers_.length > 3) ? collateralWrappers_[3] : address(0);
_collateralWrapper5 = (collateralWrappers_.length > 4) ? collateralWrappers_[4] : address(0);
_initialized = true;
}
function initialize(
uint64 auctionDuration_,
uint64 timeExtensionWindow_,
uint64 timeExtension_,
uint64 minimumBidBasisPoints_
) external {
require(!_initialized, "Already initialized");
if (auctionDuration_ <= timeExtensionWindow_) revert InvalidParameters();
if (timeExtension_ <= timeExtensionWindow_) revert InvalidParameters();
if (auctionDuration_ == 0) revert InvalidParameters();
_initialized = true;
_auctionDuration = auctionDuration_;
_timeExtensionWindow = timeExtensionWindow_;
_timeExtension = timeExtension_;
_minimumBidBasisPoints = minimumBidBasisPoints_;
}
function auctionDuration() external view returns (uint64) {
return _auctionDuration;
}
function timeExtensionWindow() external view returns (uint64) {
return _timeExtensionWindow;
}
function timeExtension() external view returns (uint64) {
return _timeExtension;
}
function minimumBidBasisPoints() external view returns (uint64) {
return _minimumBidBasisPoints;
}
function liquidations(bytes32 liquidationHash) external view returns (Liquidation memory) {
return _liquidations[liquidationHash];
}
function auctions(address collateralToken, uint256 collateralTokenId) external view returns (Auction memory) {
return _auctions[collateralToken][collateralTokenId];
}
function _isCollateralWrapper(address collateralToken) internal view returns (bool) {
return
collateralToken == _collateralWrapper1 ||
collateralToken == _collateralWrapper2 ||
collateralToken == _collateralWrapper3 ||
collateralToken == _collateralWrapper4 ||
collateralToken == _collateralWrapper5;
}
function _liquidationHash(address collateralToken, uint256 collateralTokenId) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.chainid, collateralToken, collateralTokenId, block.timestamp));
}
function _liquidationContextHash(bytes calldata liquidationContext) internal view returns (bytes32) {
return keccak256(abi.encodePacked(block.chainid, liquidationContext));
}
function _createAuction(bytes32 liquidationHash, address collateralToken, uint256 collateralTokenId) internal {
if (_auctions[collateralToken][collateralTokenId].liquidationHash != bytes32(0)) revert InvalidAuction();
_auctions[collateralToken][collateralTokenId] = Auction({
liquidationHash: liquidationHash,
endTime: 0,
highestBidder: address(0),
highestBid: 0
});
}
function _createAuction(bytes32 liquidationHash, address collateralToken, uint256 collateralTokenId) internal {
if (_auctions[collateralToken][collateralTokenId].liquidationHash != bytes32(0)) revert InvalidAuction();
_auctions[collateralToken][collateralTokenId] = Auction({
liquidationHash: liquidationHash,
endTime: 0,
highestBidder: address(0),
highestBid: 0
});
}
emit AuctionCreated(liquidationHash, collateralToken, collateralTokenId);
function _processLiquidation(Auction memory auction_, bytes calldata liquidationContext) internal {
Liquidation memory liquidation_ = _liquidations[auction_.liquidationHash];
if (liquidation_.source == address(0)) revert InvalidClaim();
if (liquidation_.liquidationContextHash != _liquidationContextHash(liquidationContext)) revert InvalidClaim();
if (liquidation_.auctionCount - 1 == 0) {
uint256 proceeds = liquidation_.proceeds + auction_.highestBid;
IERC20(liquidation_.currencyToken).safeTransfer(liquidation_.source, proceeds);
if (
Address.isContract(liquidation_.source) &&
ERC165Checker.supportsInterface(liquidation_.source, type(ICollateralLiquidationReceiver).interfaceId)
) ICollateralLiquidationReceiver(liquidation_.source).onCollateralLiquidated(liquidationContext, proceeds);
delete _liquidations[auction_.liquidationHash];
emit LiquidationEnded(auction_.liquidationHash, proceeds);
_liquidations[auction_.liquidationHash].proceeds += auction_.highestBid;
_liquidations[auction_.liquidationHash].auctionCount -= 1;
}
function _processLiquidation(Auction memory auction_, bytes calldata liquidationContext) internal {
Liquidation memory liquidation_ = _liquidations[auction_.liquidationHash];
if (liquidation_.source == address(0)) revert InvalidClaim();
if (liquidation_.liquidationContextHash != _liquidationContextHash(liquidationContext)) revert InvalidClaim();
if (liquidation_.auctionCount - 1 == 0) {
uint256 proceeds = liquidation_.proceeds + auction_.highestBid;
IERC20(liquidation_.currencyToken).safeTransfer(liquidation_.source, proceeds);
if (
Address.isContract(liquidation_.source) &&
ERC165Checker.supportsInterface(liquidation_.source, type(ICollateralLiquidationReceiver).interfaceId)
) ICollateralLiquidationReceiver(liquidation_.source).onCollateralLiquidated(liquidationContext, proceeds);
delete _liquidations[auction_.liquidationHash];
emit LiquidationEnded(auction_.liquidationHash, proceeds);
_liquidations[auction_.liquidationHash].proceeds += auction_.highestBid;
_liquidations[auction_.liquidationHash].auctionCount -= 1;
}
} else {
}
function name() external pure returns (string memory) {
return "EnglishAuctionCollateralLiquidator";
}
function liquidate(
address currencyToken,
address collateralToken,
uint256 collateralTokenId,
bytes calldata collateralWrapperContext,
bytes calldata liquidationContext
) external nonReentrant {
if (collateralToken == address(0) || currencyToken == address(0)) revert InvalidToken();
bytes32 liquidationHash = _liquidationHash(collateralToken, collateralTokenId);
if (_liquidations[liquidationHash].source != address(0)) revert InvalidLiquidation();
address underlyingCollateralToken;
uint256[] memory underlyingCollateralTokenIds;
bool isCollateralWrapper = _isCollateralWrapper(collateralToken);
if (isCollateralWrapper) {
(underlyingCollateralToken, underlyingCollateralTokenIds) = ICollateralWrapper(collateralToken).enumerate(
collateralTokenId,
collateralWrapperContext
);
underlyingCollateralToken = collateralToken;
underlyingCollateralTokenIds = new uint256[](1);
underlyingCollateralTokenIds[0] = collateralTokenId;
liquidationHash,
msg.sender,
liquidationContextHash,
currencyToken,
uint16(underlyingCollateralTokenIds.length)
);
for (uint16 i = 0; i < underlyingCollateralTokenIds.length; i++) {
_createAuction(liquidationHash, underlyingCollateralToken, underlyingCollateralTokenIds[i]);
}
_liquidations[liquidationHash] = Liquidation({
source: msg.sender,
currencyToken: currencyToken,
auctionCount: uint16(underlyingCollateralTokenIds.length),
liquidationContextHash: liquidationContextHash,
proceeds: 0
});
ICollateralWrapper(collateralToken).unwrap(collateralTokenId, collateralWrapperContext);
}
function liquidate(
address currencyToken,
address collateralToken,
uint256 collateralTokenId,
bytes calldata collateralWrapperContext,
bytes calldata liquidationContext
) external nonReentrant {
if (collateralToken == address(0) || currencyToken == address(0)) revert InvalidToken();
bytes32 liquidationHash = _liquidationHash(collateralToken, collateralTokenId);
if (_liquidations[liquidationHash].source != address(0)) revert InvalidLiquidation();
address underlyingCollateralToken;
uint256[] memory underlyingCollateralTokenIds;
bool isCollateralWrapper = _isCollateralWrapper(collateralToken);
if (isCollateralWrapper) {
(underlyingCollateralToken, underlyingCollateralTokenIds) = ICollateralWrapper(collateralToken).enumerate(
collateralTokenId,
collateralWrapperContext
);
underlyingCollateralToken = collateralToken;
underlyingCollateralTokenIds = new uint256[](1);
underlyingCollateralTokenIds[0] = collateralTokenId;
liquidationHash,
msg.sender,
liquidationContextHash,
currencyToken,
uint16(underlyingCollateralTokenIds.length)
);
for (uint16 i = 0; i < underlyingCollateralTokenIds.length; i++) {
_createAuction(liquidationHash, underlyingCollateralToken, underlyingCollateralTokenIds[i]);
}
_liquidations[liquidationHash] = Liquidation({
source: msg.sender,
currencyToken: currencyToken,
auctionCount: uint16(underlyingCollateralTokenIds.length),
liquidationContextHash: liquidationContextHash,
proceeds: 0
});
ICollateralWrapper(collateralToken).unwrap(collateralTokenId, collateralWrapperContext);
}
} else {
}
bytes32 liquidationContextHash = _liquidationContextHash(liquidationContext);
emit LiquidationStarted(
function liquidate(
address currencyToken,
address collateralToken,
uint256 collateralTokenId,
bytes calldata collateralWrapperContext,
bytes calldata liquidationContext
) external nonReentrant {
if (collateralToken == address(0) || currencyToken == address(0)) revert InvalidToken();
bytes32 liquidationHash = _liquidationHash(collateralToken, collateralTokenId);
if (_liquidations[liquidationHash].source != address(0)) revert InvalidLiquidation();
address underlyingCollateralToken;
uint256[] memory underlyingCollateralTokenIds;
bool isCollateralWrapper = _isCollateralWrapper(collateralToken);
if (isCollateralWrapper) {
(underlyingCollateralToken, underlyingCollateralTokenIds) = ICollateralWrapper(collateralToken).enumerate(
collateralTokenId,
collateralWrapperContext
);
underlyingCollateralToken = collateralToken;
underlyingCollateralTokenIds = new uint256[](1);
underlyingCollateralTokenIds[0] = collateralTokenId;
liquidationHash,
msg.sender,
liquidationContextHash,
currencyToken,
uint16(underlyingCollateralTokenIds.length)
);
for (uint16 i = 0; i < underlyingCollateralTokenIds.length; i++) {
_createAuction(liquidationHash, underlyingCollateralToken, underlyingCollateralTokenIds[i]);
}
_liquidations[liquidationHash] = Liquidation({
source: msg.sender,
currencyToken: currencyToken,
auctionCount: uint16(underlyingCollateralTokenIds.length),
liquidationContextHash: liquidationContextHash,
proceeds: 0
});
ICollateralWrapper(collateralToken).unwrap(collateralTokenId, collateralWrapperContext);
}
function liquidate(
address currencyToken,
address collateralToken,
uint256 collateralTokenId,
bytes calldata collateralWrapperContext,
bytes calldata liquidationContext
) external nonReentrant {
if (collateralToken == address(0) || currencyToken == address(0)) revert InvalidToken();
bytes32 liquidationHash = _liquidationHash(collateralToken, collateralTokenId);
if (_liquidations[liquidationHash].source != address(0)) revert InvalidLiquidation();
address underlyingCollateralToken;
uint256[] memory underlyingCollateralTokenIds;
bool isCollateralWrapper = _isCollateralWrapper(collateralToken);
if (isCollateralWrapper) {
(underlyingCollateralToken, underlyingCollateralTokenIds) = ICollateralWrapper(collateralToken).enumerate(
collateralTokenId,
collateralWrapperContext
);
underlyingCollateralToken = collateralToken;
underlyingCollateralTokenIds = new uint256[](1);
underlyingCollateralTokenIds[0] = collateralTokenId;
liquidationHash,
msg.sender,
liquidationContextHash,
currencyToken,
uint16(underlyingCollateralTokenIds.length)
);
for (uint16 i = 0; i < underlyingCollateralTokenIds.length; i++) {
_createAuction(liquidationHash, underlyingCollateralToken, underlyingCollateralTokenIds[i]);
}
_liquidations[liquidationHash] = Liquidation({
source: msg.sender,
currencyToken: currencyToken,
auctionCount: uint16(underlyingCollateralTokenIds.length),
liquidationContextHash: liquidationContextHash,
proceeds: 0
});
ICollateralWrapper(collateralToken).unwrap(collateralTokenId, collateralWrapperContext);
}
IERC721(collateralToken).transferFrom(msg.sender, address(this), collateralTokenId);
if (isCollateralWrapper)
function bid(address collateralToken, uint256 collateralTokenId, uint256 amount) external nonReentrant {
Auction memory auction_ = _auctions[collateralToken][collateralTokenId];
Liquidation memory liquidation_ = _liquidations[auction_.liquidationHash];
if (liquidation_.source == address(0)) revert InvalidAuction();
if (auction_.liquidationHash == bytes32(0)) revert InvalidAuction();
if (auction_.endTime != 0 && auction_.endTime < uint64(block.timestamp)) revert InvalidBid();
if (
amount <= auction_.highestBid ||
amount - auction_.highestBid < (auction_.highestBid * _minimumBidBasisPoints) / BASIS_POINTS_SCALE
) revert InvalidBid();
if (auction_.endTime == 0) {
uint64 endTime = uint64(block.timestamp) + _auctionDuration;
_auctions[collateralToken][collateralTokenId].endTime = endTime;
emit AuctionStarted(auction_.liquidationHash, collateralToken, collateralTokenId, endTime);
uint64 endTime = uint64(block.timestamp) + _timeExtension;
_auctions[collateralToken][collateralTokenId].endTime = endTime;
emit AuctionExtended(auction_.liquidationHash, collateralToken, collateralTokenId, endTime);
_auctions[collateralToken][collateralTokenId].highestBid = amount;
if (auction_.highestBidder != address(0)) {
IERC20(liquidation_.currencyToken).safeTransfer(auction_.highestBidder, auction_.highestBid);
}
function bid(address collateralToken, uint256 collateralTokenId, uint256 amount) external nonReentrant {
Auction memory auction_ = _auctions[collateralToken][collateralTokenId];
Liquidation memory liquidation_ = _liquidations[auction_.liquidationHash];
if (liquidation_.source == address(0)) revert InvalidAuction();
if (auction_.liquidationHash == bytes32(0)) revert InvalidAuction();
if (auction_.endTime != 0 && auction_.endTime < uint64(block.timestamp)) revert InvalidBid();
if (
amount <= auction_.highestBid ||
amount - auction_.highestBid < (auction_.highestBid * _minimumBidBasisPoints) / BASIS_POINTS_SCALE
) revert InvalidBid();
if (auction_.endTime == 0) {
uint64 endTime = uint64(block.timestamp) + _auctionDuration;
_auctions[collateralToken][collateralTokenId].endTime = endTime;
emit AuctionStarted(auction_.liquidationHash, collateralToken, collateralTokenId, endTime);
uint64 endTime = uint64(block.timestamp) + _timeExtension;
_auctions[collateralToken][collateralTokenId].endTime = endTime;
emit AuctionExtended(auction_.liquidationHash, collateralToken, collateralTokenId, endTime);
_auctions[collateralToken][collateralTokenId].highestBid = amount;
if (auction_.highestBidder != address(0)) {
IERC20(liquidation_.currencyToken).safeTransfer(auction_.highestBidder, auction_.highestBid);
}
} else if (auction_.endTime - uint64(block.timestamp) <= _timeExtensionWindow) {
}
_auctions[collateralToken][collateralTokenId].highestBidder = msg.sender;
function bid(address collateralToken, uint256 collateralTokenId, uint256 amount) external nonReentrant {
Auction memory auction_ = _auctions[collateralToken][collateralTokenId];
Liquidation memory liquidation_ = _liquidations[auction_.liquidationHash];
if (liquidation_.source == address(0)) revert InvalidAuction();
if (auction_.liquidationHash == bytes32(0)) revert InvalidAuction();
if (auction_.endTime != 0 && auction_.endTime < uint64(block.timestamp)) revert InvalidBid();
if (
amount <= auction_.highestBid ||
amount - auction_.highestBid < (auction_.highestBid * _minimumBidBasisPoints) / BASIS_POINTS_SCALE
) revert InvalidBid();
if (auction_.endTime == 0) {
uint64 endTime = uint64(block.timestamp) + _auctionDuration;
_auctions[collateralToken][collateralTokenId].endTime = endTime;
emit AuctionStarted(auction_.liquidationHash, collateralToken, collateralTokenId, endTime);
uint64 endTime = uint64(block.timestamp) + _timeExtension;
_auctions[collateralToken][collateralTokenId].endTime = endTime;
emit AuctionExtended(auction_.liquidationHash, collateralToken, collateralTokenId, endTime);
_auctions[collateralToken][collateralTokenId].highestBid = amount;
if (auction_.highestBidder != address(0)) {
IERC20(liquidation_.currencyToken).safeTransfer(auction_.highestBidder, auction_.highestBid);
}
}
IERC20(liquidation_.currencyToken).safeTransferFrom(msg.sender, address(this), amount);
emit AuctionBid(auction_.liquidationHash, collateralToken, collateralTokenId, msg.sender, amount);
function claim(
address collateralToken,
uint256 collateralTokenId,
bytes calldata liquidationContext
) external nonReentrant {
Auction memory auction_ = _auctions[collateralToken][collateralTokenId];
if (auction_.liquidationHash == bytes32(0)) revert InvalidAuction();
if (auction_.highestBidder == address(0)) revert InvalidClaim();
if (uint64(block.timestamp) <= auction_.endTime) revert InvalidClaim();
_processLiquidation(auction_, liquidationContext);
delete _auctions[collateralToken][collateralTokenId];
IERC721(collateralToken).transferFrom(address(this), auction_.highestBidder, collateralTokenId);
emit AuctionEnded(
auction_.liquidationHash,
collateralToken,
collateralTokenId,
auction_.highestBidder,
auction_.highestBid
);
}
}
| 9,659,293 | [
1,
664,
13740,
432,
4062,
17596,
2045,
287,
511,
18988,
350,
639,
225,
6565,
30719,
511,
5113,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
24151,
37,
4062,
13535,
2045,
287,
48,
18988,
350,
639,
353,
467,
13535,
2045,
287,
48,
18988,
350,
639,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
203,
565,
533,
1071,
5381,
15694,
7618,
2689,
67,
5757,
273,
315,
21,
18,
21,
14432,
203,
203,
565,
2254,
5034,
2713,
5381,
28143,
15664,
67,
8941,
55,
67,
19378,
273,
1728,
67,
3784,
31,
203,
203,
203,
565,
555,
1962,
2402,
5621,
203,
203,
565,
555,
1962,
1345,
5621,
203,
203,
565,
555,
1962,
37,
4062,
5621,
203,
203,
565,
555,
1962,
48,
18988,
350,
367,
5621,
203,
203,
565,
555,
1962,
17763,
5621,
203,
203,
565,
555,
1962,
9762,
5621,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
3462,
31,
203,
565,
1958,
432,
4062,
288,
203,
3639,
1731,
1578,
4501,
26595,
367,
2310,
31,
203,
3639,
2254,
1105,
13859,
31,
203,
3639,
1758,
9742,
17763,
765,
31,
203,
3639,
2254,
5034,
9742,
17763,
31,
203,
565,
289,
203,
203,
565,
1958,
511,
18988,
350,
367,
288,
203,
3639,
1758,
1084,
31,
203,
3639,
1758,
5462,
1345,
31,
203,
3639,
2254,
2313,
279,
4062,
1380,
31,
203,
3639,
1731,
1578,
4501,
26595,
367,
1042,
2310,
31,
203,
3639,
2254,
5034,
11247,
87,
31,
203,
565,
289,
203,
203,
3639,
1731,
1578,
8808,
4501,
26595,
367,
2310,
16,
203,
3639,
1758,
8808,
1084,
16,
203,
3639,
1731,
1578,
8808,
4501,
26595,
367,
1042,
2310,
16,
203,
3639,
1758,
5462,
2
]
|
./full_match/5/0x631CadF9267a7784D690AFa0Bd9128760CF555Cf/sources/contracts/libraries/Token.sol | * @dev Returns ownership struct hash./ | function hash(Owner memory _owner) internal pure returns (bytes32) {
return keccak256(abi.encode(OWNER_TYPE_HASH, _owner.addr, _owner.tokenAddr, _owner.chainId));
}
| 1,908,481 | [
1,
1356,
23178,
1958,
1651,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1651,
12,
5541,
3778,
389,
8443,
13,
2713,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
565,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
29602,
67,
2399,
67,
15920,
16,
389,
8443,
18,
4793,
16,
389,
8443,
18,
2316,
3178,
16,
389,
8443,
18,
5639,
548,
10019,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Ethereum Name Service contracts by Nick Johnson <[email protected]>
//
// To the extent possible under law, the person who associated CC0 with
// ENS contracts has waived all copyright and related or neighboring rights
// to ENS.
//
// You should have received a copy of the CC0 legalcode along with this
// work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
/**
* The ENS registry contract.
*/
contract ENS {
struct Record {
address owner;
address resolver;
}
mapping(bytes32=>Record) records;
// 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 owner of a node changes the resolver for that node.
event NewResolver(bytes32 indexed node, address resolver);
// 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, with the provided address as the owner of the root node.
*/
function ENS(address owner) {
records[0].owner = owner;
}
/**
* 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;
}
/**
* 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;
}
}
/**
* A registrar that allocates subdomains to the first person to claim them. It also deploys
* a simple resolver contract and sets that as the default resolver on new names for
* convenience.
*/
contract FIFSRegistrar {
ENS ens;
PublicResolver defaultResolver;
bytes32 rootNode;
/**
* Constructor.
* @param ensAddr The address of the ENS registry.
* @param node The node that this registrar administers.
*/
function FIFSRegistrar(address ensAddr, bytes32 node) {
ens = ENS(ensAddr);
defaultResolver = new PublicResolver(ensAddr);
rootNode = node;
}
/**
* Register a name, or change the owner of an existing registration.
* @param subnode The hash of the label to register.
* @param owner The address of the new owner.
*/
function register(bytes32 subnode, address owner) {
var node = sha3(rootNode, subnode);
var currentOwner = ens.owner(node);
if(currentOwner != 0 && currentOwner != msg.sender)
throw;
// Temporarily set ourselves as the owner
ens.setSubnodeOwner(rootNode, subnode, this);
// Set up the default resolver
ens.setResolver(node, defaultResolver);
// Set the owner to the real owner
ens.setOwner(node, owner);
}
}
contract Resolver {
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
function has(bytes32 node, bytes32 kind) returns (bool);
function addr(bytes32 node) constant returns (address ret);
function content(bytes32 node) constant returns (bytes32 ret);
}
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is Resolver {
ENS ens;
mapping(bytes32=>address) addresses;
mapping(bytes32=>bytes32) contents;
modifier only_owner(bytes32 node) {
if(ens.owner(node) != msg.sender) throw;
_
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(address ensAddr) {
ens = 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) returns (bool) {
return (kind == "addr" && addresses[node] != 0) ||
(kind == "content" && contents[node] != 0);
}
/**
* 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];
if(ret == 0)
throw;
}
/**
* Returns the content hash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) constant returns (bytes32 ret) {
ret = contents[node];
if(ret == 0)
throw;
}
/**
* 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;
AddrChanged(node, addr);
}
/**
* Sets the content hash 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 hash The content hash to set.
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) {
contents[node] = hash;
ContentChanged(node, hash);
}
}
| * 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];
if(ret == 0)
throw;
}
| 1,754,415 | [
1,
1356,
326,
1758,
3627,
598,
392,
512,
3156,
756,
18,
225,
756,
1021,
512,
3156,
756,
358,
843,
18,
327,
1021,
3627,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3091,
12,
3890,
1578,
756,
13,
5381,
1135,
261,
2867,
325,
13,
288,
203,
3639,
325,
273,
6138,
63,
2159,
15533,
203,
3639,
309,
12,
1349,
422,
374,
13,
203,
5411,
604,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/77/0xe0cA274c73938688D7dA3829959E98706998b989/sources/contracts/upgradeable/AssetUpgradeable.sol | @dev Allows to set the contract props @param what The contract prop @param data The prop value | function set(bytes32 what, address data) external authorized {
if (what == 'ledger') {
ledger = LedgerLike(data);
asset = WrappedErc20Like(data);
revert InvalidWhat();
}
}
| 5,048,340 | [
1,
19132,
358,
444,
326,
6835,
3458,
225,
4121,
1021,
6835,
2270,
225,
501,
1021,
2270,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
444,
12,
3890,
1578,
4121,
16,
1758,
501,
13,
3903,
10799,
288,
203,
565,
309,
261,
23770,
422,
296,
1259,
693,
6134,
288,
203,
1377,
16160,
273,
511,
329,
693,
8804,
12,
892,
1769,
203,
1377,
3310,
273,
24506,
41,
1310,
3462,
8804,
12,
892,
1769,
203,
1377,
15226,
1962,
23801,
5621,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x656530A527Dc6f30BFBCF67a45afe8fBD4d1224D/sources/src/Orb.sol | @notice Function to withdraw all beneficiary funds on the contract. Settles if possible. @dev Allowed for anyone at any time, does not use `msg.sender` in its execution. | function withdrawAllForBeneficiary() external virtual {
if (keeper != address(this)) {
_settle();
}
_withdraw(beneficiary, fundsOf[beneficiary]);
}
| 8,361,151 | [
1,
2083,
358,
598,
9446,
777,
27641,
74,
14463,
814,
284,
19156,
603,
326,
6835,
18,
1000,
88,
1040,
309,
3323,
18,
1377,
16740,
364,
1281,
476,
622,
1281,
813,
16,
1552,
486,
999,
1375,
3576,
18,
15330,
68,
316,
2097,
4588,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
1595,
1290,
38,
4009,
74,
14463,
814,
1435,
3903,
5024,
288,
203,
3639,
309,
261,
79,
9868,
480,
1758,
12,
2211,
3719,
288,
203,
5411,
389,
542,
5929,
5621,
203,
3639,
289,
203,
3639,
389,
1918,
9446,
12,
70,
4009,
74,
14463,
814,
16,
284,
19156,
951,
63,
70,
4009,
74,
14463,
814,
19226,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0xF25BC3059Cc041d17Eb253d8883546412102b9D7/sources/cBNB_TOKEN.sol | * @dev Destroys `amount` tokens from `account`, reducing the total supply. Emits a {Transfer} event with `to` set to the zero address. Requirements - `account` cannot be the zero address. - `account` must have at least `amount` tokens./ | function _burn(address account, uint256 amount) internal {
require(account != address(0), 'BEP20: burn from the zero address');
_balances[account] = _balances[account].cBNB(amount, 'BEP20: burn amount exceeds balance');
_totalSupply = _totalSupply.cBNB(amount);
emit Transfer(account, address(0), amount);
}
| 11,246,915 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
4631,
9191,
9299,
2822,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
869,
68,
444,
358,
326,
3634,
1758,
18,
29076,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
296,
5948,
52,
3462,
30,
18305,
628,
326,
3634,
1758,
8284,
203,
203,
3639,
389,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
71,
15388,
38,
12,
8949,
16,
296,
5948,
52,
3462,
30,
18305,
3844,
14399,
11013,
8284,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
71,
15388,
38,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "solmate/tokens/ERC721.sol";
import "./interfaces/ILendWrapper.sol";
import "./interfaces/IERC721.sol";
import "./interfaces/IERC721Receiver.sol";
import "./interfaces/IERC165.sol";
contract LendWrapper is ERC721, ILendWrapper, IERC721Receiver {
IERC721 private wrappedToken;
/// @notice Stores the address of the original depositor of each managed NFT.
mapping(uint256 => address) public originalOwner;
/// @notice Stores lending durations for each managed tokenId
/// @dev The mappings can be invalidated if borrowers call `terminateLending`
mapping(uint256 => LendingDuration) public lendingDurations;
// ----------------------------- Structs ----------------------------- //
struct LendingDuration {
uint256 startTime;
uint256 endTime;
}
// ----------------------------- Events ----------------------------- //
event Lent(address indexed lender, address indexed borrower, uint256 indexed tokenId, uint256 startTime, uint256 endTime);
event Collected(address indexed lender, uint256 indexed tokenId);
event LendingTerminated(address indexed borrower, uint256 indexed tokenId);
// ----------------------------- Constructor ----------------------------- //
constructor(
address _wrappedTokenAddress,
string memory _name,
string memory _symbol) ERC721(_name, _symbol) {
wrappedToken = IERC721(_wrappedTokenAddress);
}
// ----------------------------- View Functions ----------------------------- //
function underlyingToken() public view override returns (address) {
return address(wrappedToken);
}
function tokenURI(uint256 id) public view override returns (string memory) {
return wrappedToken.tokenURI(id);
}
function canBeCollected(
uint256 _tokenId
) public view returns (bool) {
require(originalOwner[_tokenId] != address(0), "Unmanaged Token Id"); // Results are invalid if token isn't being managed by this contract
return virtualOwnerOf(_tokenId) == originalOwner[_tokenId];
}
function virtualOwnerOf(uint256 _tokenId) public view returns (address) {
return virtualOwnerAtTime(_tokenId, block.timestamp);
}
// @notice Used to get the address of an unmanaged NFT, supports looking up other ILendWrappers.
function getOwnerOfUnmanagedNFT(uint256 _tokenId) internal view returns (address) {
address nftDirectOwner = wrappedToken.ownerOf(_tokenId);
if (isContract(nftDirectOwner)) {
if (IERC165(nftDirectOwner).supportsInterface(0x48bbd5ac)) { // Check for ILendWrapper interface
return ILendWrapper(nftDirectOwner).virtualOwnerOf(_tokenId);
}
}
return nftDirectOwner;
}
function virtualOwnerAtTime(uint256 _tokenId, uint256 _timeToCheck) public view returns (address) {
if (originalOwner[_tokenId] != address(0)) { // This means that the tokenId is managed by this contract
LendingDuration memory duration = lendingDurations[_tokenId];
if (duration.endTime != 0 // duration is found and active
&& duration.startTime <= _timeToCheck && _timeToCheck < duration.endTime // duration is within time range
) {
return ownerOf[_tokenId]; // owner of the wrapper NFT
} else {
return originalOwner[_tokenId]; // orignal owner of the wrapped NFT
}
} else {
return getOwnerOfUnmanagedNFT(_tokenId); // unmanaged NFT - return owner as informed by the wrapped NFT
}
}
// ----------------------------- Mutative Functions ----------------------------- //
function lendOut(
uint256 _tokenId,
address _borrower,
uint256 _startTime,
uint256 _durationInSeconds
) external {
require(_durationInSeconds != 0, "Duration must > 0");
uint256 endTime = _startTime + _durationInSeconds;
require(endTime > block.timestamp, "Lending period expired");
originalOwner[_tokenId] = msg.sender;
lendingDurations[_tokenId] = LendingDuration(_startTime, endTime);
_mint(_borrower, _tokenId);
emit Lent(msg.sender, _borrower, _tokenId, _startTime, endTime);
wrappedToken.transferFrom(msg.sender, address(this), _tokenId);
}
function terminateLending(
uint256 _tokenId
) external {
require(ownerOf[_tokenId] == msg.sender, "Only borrower can terminate");
require(block.timestamp < lendingDurations[_tokenId].endTime, "Lending already expired");
delete lendingDurations[_tokenId];
emit LendingTerminated(msg.sender, _tokenId);
}
function collect(
uint256 _tokenId
) external {
require(canBeCollected(_tokenId), "Token can't be collected");
address owner = originalOwner[_tokenId];
originalOwner[_tokenId] = address(0);
delete lendingDurations[_tokenId];
_burn(_tokenId);
emit Collected(owner, _tokenId);
wrappedToken.transferFrom(address(this), owner, _tokenId); // should be safe as it originated from the owner address
}
// ----------------------------- Utility ----------------------------- //
/// @dev As a recipient of ERC721.safeTransfer();
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
require(msg.sender == address(wrappedToken), "Only supports wrapped");
return IERC721Receiver(operator).onERC721Received.selector;
}
function supportsInterface(bytes4 interfaceID) public pure override returns (bool) {
return
interfaceID == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceID == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceID == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata
interfaceID == 0x48bbd5ac; // ERC165 Interface ID for ILendWrapper
}
function isContract(address addr) private view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
| ----------------------------- Structs ----------------------------- | contract LendWrapper is ERC721, ILendWrapper, IERC721Receiver {
IERC721 private wrappedToken;
mapping(uint256 => address) public originalOwner;
mapping(uint256 => LendingDuration) public lendingDurations;
pragma solidity 0.8.11;
struct LendingDuration {
uint256 startTime;
uint256 endTime;
}
event Collected(address indexed lender, uint256 indexed tokenId);
event LendingTerminated(address indexed borrower, uint256 indexed tokenId);
address _wrappedTokenAddress,
string memory _name,
event Lent(address indexed lender, address indexed borrower, uint256 indexed tokenId, uint256 startTime, uint256 endTime);
constructor(
string memory _symbol) ERC721(_name, _symbol) {
wrappedToken = IERC721(_wrappedTokenAddress);
}
function underlyingToken() public view override returns (address) {
return address(wrappedToken);
}
function tokenURI(uint256 id) public view override returns (string memory) {
return wrappedToken.tokenURI(id);
}
function canBeCollected(
uint256 _tokenId
) public view returns (bool) {
return virtualOwnerOf(_tokenId) == originalOwner[_tokenId];
}
function virtualOwnerOf(uint256 _tokenId) public view returns (address) {
return virtualOwnerAtTime(_tokenId, block.timestamp);
}
function getOwnerOfUnmanagedNFT(uint256 _tokenId) internal view returns (address) {
address nftDirectOwner = wrappedToken.ownerOf(_tokenId);
if (isContract(nftDirectOwner)) {
return ILendWrapper(nftDirectOwner).virtualOwnerOf(_tokenId);
}
}
return nftDirectOwner;
function getOwnerOfUnmanagedNFT(uint256 _tokenId) internal view returns (address) {
address nftDirectOwner = wrappedToken.ownerOf(_tokenId);
if (isContract(nftDirectOwner)) {
return ILendWrapper(nftDirectOwner).virtualOwnerOf(_tokenId);
}
}
return nftDirectOwner;
}
| 14,086,858 | [
1,
1271,
16982,
7362,
87,
12146,
7620,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
511,
409,
3611,
353,
4232,
39,
27,
5340,
16,
467,
48,
409,
3611,
16,
467,
654,
39,
27,
5340,
12952,
288,
203,
203,
565,
467,
654,
39,
27,
5340,
3238,
5805,
1345,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
1071,
2282,
5541,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
511,
2846,
5326,
13,
1071,
328,
2846,
5326,
87,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2499,
31,
203,
565,
1958,
511,
2846,
5326,
288,
203,
3639,
2254,
5034,
8657,
31,
203,
3639,
2254,
5034,
13859,
31,
203,
565,
289,
203,
203,
565,
871,
9302,
329,
12,
2867,
8808,
328,
2345,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
565,
871,
511,
2846,
21888,
12,
2867,
8808,
29759,
264,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
3639,
1758,
389,
18704,
1345,
1887,
16,
203,
3639,
533,
3778,
389,
529,
16,
203,
565,
871,
511,
319,
12,
2867,
8808,
328,
2345,
16,
1758,
8808,
29759,
264,
16,
2254,
5034,
8808,
1147,
548,
16,
2254,
5034,
8657,
16,
2254,
5034,
13859,
1769,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
7175,
13,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
288,
203,
3639,
5805,
1345,
273,
467,
654,
39,
27,
5340,
24899,
18704,
1345,
1887,
1769,
203,
565,
289,
203,
203,
565,
445,
6808,
1345,
1435,
1071,
1476,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1758,
12,
18704,
1345,
1769,
203,
565,
289,
203,
203,
565,
445,
1147,
3098,
2
]
|
./full_match/137/0x16D66b01664bc834f5db13D01E51E1Fa7C44f03B/sources/browser/NFT721.sol | @dev See {IERC721-approve}./ | function approve(address to, uint256 tokenId) public virtual override {
address owner = 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);
}
| 4,781,994 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
12908,
537,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1377,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
5024,
3849,
288,
203,
1377,
1758,
3410,
273,
3410,
951,
12,
2316,
548,
1769,
203,
1377,
2583,
12,
869,
480,
3410,
16,
315,
654,
39,
27,
5340,
30,
23556,
358,
783,
3410,
8863,
203,
203,
1377,
2583,
24899,
3576,
12021,
1435,
422,
3410,
747,
353,
31639,
1290,
1595,
12,
8443,
16,
389,
3576,
12021,
1435,
3631,
203,
1850,
315,
654,
39,
27,
5340,
30,
6617,
537,
4894,
353,
486,
3410,
12517,
20412,
364,
777,
6,
203,
1377,
11272,
203,
203,
1377,
389,
12908,
537,
12,
869,
16,
1147,
548,
1769,
203,
1377,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "./Interfaces/ISortedTroves.sol";
import "./Interfaces/ITroveManager.sol";
import "./Interfaces/IBorrowerOperations.sol";
import "./Dependencies/SafeMath.sol";
import "./Dependencies/Ownable.sol";
import "./Dependencies/CheckContract.sol";
import "./Dependencies/console.sol";
/*
* A sorted doubly linked list with nodes sorted in descending order.
*
* Nodes map to active Troves in the system - the ID property is the address of a Trove owner.
* Nodes are ordered according to their current nominal individual collateral ratio (NICR),
* which is like the ICR but without the price, i.e., just collateral / debt.
*
* The list optionally accepts insert position hints.
*
* NICRs are computed dynamically at runtime, and not stored on the Node. This is because NICRs of active Troves
* change dynamically as liquidation events occur.
*
* The list relies on the fact that liquidation events preserve ordering: a liquidation decreases the NICRs of all active Troves,
* but maintains their order. A node inserted based on current NICR will maintain the correct position,
* relative to it's peers, as rewards accumulate, as long as it's raw collateral and debt have not changed.
* Thus, Nodes remain sorted by current NICR.
*
* Nodes need only be re-inserted upon a Trove operation - when the owner adds or removes collateral or debt
* to their position.
*
* The list is a modification of the following audited SortedDoublyLinkedList:
* https://github.com/livepeer/protocol/blob/master/contracts/libraries/SortedDoublyLL.sol
*
*
* Changes made in the Liquity implementation:
*
* - Keys have been removed from nodes
*
* - Ordering checks for insertion are performed by comparing an NICR argument to the current NICR, calculated at runtime.
* The list relies on the property that ordering by ICR is maintained as the ETH:USD price varies.
*
* - Public functions with parameters have been made internal to save gas, and given an external wrapper function for external access
*/
contract SortedTroves is Ownable, CheckContract, ISortedTroves {
using SafeMath for uint256;
string constant public NAME = "SortedTroves";
event TroveManagerAddressChanged(address _troveManagerAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
address public borrowerOperationsAddress;
ITroveManager public troveManager;
// Information for a node in the list
struct Node {
bool exists;
address nextId; // Id of next node (smaller NICR) in the list
address prevId; // Id of previous node (larger NICR) in the list
}
// Information for the list
struct Data {
address head; // Head of the list. Also the node in the list with the largest NICR
address tail; // Tail of the list. Also the node in the list with the smallest NICR
uint256 maxSize; // Maximum size of the list
uint256 size; // Current size of the list
mapping (address => Node) nodes; // Track the corresponding ids for each node in the list
}
Data public data;
// --- Dependency setters ---
function setParams(uint256 _size, address _troveManagerAddress, address _borrowerOperationsAddress) external override onlyOwner {
require(_size > 0, "SortedTroves: Size can’t be zero");
checkContract(_troveManagerAddress);
checkContract(_borrowerOperationsAddress);
data.maxSize = _size;
troveManager = ITroveManager(_troveManagerAddress);
borrowerOperationsAddress = _borrowerOperationsAddress;
emit TroveManagerAddressChanged(_troveManagerAddress);
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
_renounceOwnership();
}
/*
* @dev Add a node to the list
* @param _id Node's id
* @param _NICR Node's NICR
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function insert (address _id, uint256 _NICR, address _prevId, address _nextId) external override {
ITroveManager troveManagerCached = troveManager;
_requireCallerIsBOorTroveM(troveManagerCached);
_insert(troveManagerCached, _id, _NICR, _prevId, _nextId);
}
function _insert(ITroveManager _troveManager, address _id, uint256 _NICR, address _prevId, address _nextId) internal {
// List must not be full
require(!isFull(), "SortedTroves: List is full");
// List must not already contain node
require(!contains(_id), "SortedTroves: List already contains the node");
// Node id must not be null
require(_id != address(0), "SortedTroves: Id cannot be zero");
// NICR must be non-zero
require(_NICR > 0, "SortedTroves: NICR must be positive");
address prevId = _prevId;
address nextId = _nextId;
if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
// Sender's hint was not a valid insert position
// Use sender's hint to find a valid insert position
(prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);
}
data.nodes[_id].exists = true;
if (prevId == address(0) && nextId == address(0)) {
// Insert as head and tail
data.head = _id;
data.tail = _id;
} else if (prevId == address(0)) {
// Insert before `prevId` as the head
data.nodes[_id].nextId = data.head;
data.nodes[data.head].prevId = _id;
data.head = _id;
} else if (nextId == address(0)) {
// Insert after `nextId` as the tail
data.nodes[_id].prevId = data.tail;
data.nodes[data.tail].nextId = _id;
data.tail = _id;
} else {
// Insert at insert position between `prevId` and `nextId`
data.nodes[_id].nextId = nextId;
data.nodes[_id].prevId = prevId;
data.nodes[prevId].nextId = _id;
data.nodes[nextId].prevId = _id;
}
data.size = data.size.add(1);
emit NodeAdded(_id, _NICR);
}
function remove(address _id) external override {
_requireCallerIsTroveManager();
_remove(_id);
}
/*
* @dev Remove a node from the list
* @param _id Node's id
*/
function _remove(address _id) internal {
// List must contain the node
require(contains(_id), "SortedTroves: List does not contain the id");
if (data.size > 1) {
// List contains more than a single node
if (_id == data.head) {
// The removed node is the head
// Set head to next node
data.head = data.nodes[_id].nextId;
// Set prev pointer of new head to null
data.nodes[data.head].prevId = address(0);
} else if (_id == data.tail) {
// The removed node is the tail
// Set tail to previous node
data.tail = data.nodes[_id].prevId;
// Set next pointer of new tail to null
data.nodes[data.tail].nextId = address(0);
} else {
// The removed node is neither the head nor the tail
// Set next pointer of previous node to the next node
data.nodes[data.nodes[_id].prevId].nextId = data.nodes[_id].nextId;
// Set prev pointer of next node to the previous node
data.nodes[data.nodes[_id].nextId].prevId = data.nodes[_id].prevId;
}
} else {
// List contains a single node
// Set the head and tail to null
data.head = address(0);
data.tail = address(0);
}
delete data.nodes[_id];
data.size = data.size.sub(1);
NodeRemoved(_id);
}
/*
* @dev Re-insert the node at a new position, based on its new NICR
* @param _id Node's id
* @param _newNICR Node's new NICR
* @param _prevId Id of previous node for the new insert position
* @param _nextId Id of next node for the new insert position
*/
function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external override {
ITroveManager troveManagerCached = troveManager;
_requireCallerIsBOorTroveM(troveManagerCached);
// List must contain the node
require(contains(_id), "SortedTroves: List does not contain the id");
// NICR must be non-zero
require(_newNICR > 0, "SortedTroves: NICR must be positive");
// Remove node from the list
_remove(_id);
_insert(troveManagerCached, _id, _newNICR, _prevId, _nextId);
}
/*
* @dev Checks if the list contains a node
*/
function contains(address _id) public view override returns (bool) {
return data.nodes[_id].exists;
}
/*
* @dev Checks if the list is full
*/
function isFull() public view override returns (bool) {
return data.size == data.maxSize;
}
/*
* @dev Checks if the list is empty
*/
function isEmpty() public view override returns (bool) {
return data.size == 0;
}
/*
* @dev Returns the current size of the list
*/
function getSize() external view override returns (uint256) {
return data.size;
}
/*
* @dev Returns the maximum size of the list
*/
function getMaxSize() external view override returns (uint256) {
return data.maxSize;
}
/*
* @dev Returns the first node in the list (node with the largest NICR)
*/
function getFirst() external view override returns (address) {
return data.head;
}
/*
* @dev Returns the last node in the list (node with the smallest NICR)
*/
function getLast() external view override returns (address) {
return data.tail;
}
/*
* @dev Returns the next node (with a smaller NICR) in the list for a given node
* @param _id Node's id
*/
function getNext(address _id) external view override returns (address) {
return data.nodes[_id].nextId;
}
/*
* @dev Returns the previous node (with a larger NICR) in the list for a given node
* @param _id Node's id
*/
function getPrev(address _id) external view override returns (address) {
return data.nodes[_id].prevId;
}
/*
* @dev Check if a pair of nodes is a valid insertion point for a new node with the given NICR
* @param _NICR Node's NICR
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (bool) {
return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);
}
function _validInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (bool) {
if (_prevId == address(0) && _nextId == address(0)) {
// `(null, null)` is a valid insert position if the list is empty
return isEmpty();
} else if (_prevId == address(0)) {
// `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list
return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);
} else if (_nextId == address(0)) {
// `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list
return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);
} else {
// `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_NICR` falls between the two nodes' NICRs
return data.nodes[_prevId].nextId == _nextId &&
_troveManager.getNominalICR(_prevId) >= _NICR &&
_NICR >= _troveManager.getNominalICR(_nextId);
}
}
/*
* @dev Descend the list (larger NICRs to smaller NICRs) to find a valid insert position
* @param _troveManager TroveManager contract, passed in as param to save SLOAD’s
* @param _NICR Node's NICR
* @param _startId Id of node to start descending the list from
*/
function _descendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
// If `_startId` is the head, check if the insert position is before the head
if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {
return (address(0), _startId);
}
address prevId = _startId;
address nextId = data.nodes[prevId].nextId;
// Descend the list until we reach the end or until we find a valid insert position
while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
prevId = data.nodes[prevId].nextId;
nextId = data.nodes[prevId].nextId;
}
return (prevId, nextId);
}
/*
* @dev Ascend the list (smaller NICRs to larger NICRs) to find a valid insert position
* @param _troveManager TroveManager contract, passed in as param to save SLOAD’s
* @param _NICR Node's NICR
* @param _startId Id of node to start ascending the list from
*/
function _ascendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
// If `_startId` is the tail, check if the insert position is after the tail
if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = data.nodes[nextId].prevId;
// Ascend the list until we reach the end or until we find a valid insertion point
while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
nextId = data.nodes[nextId].prevId;
prevId = data.nodes[nextId].prevId;
}
return (prevId, nextId);
}
/*
* @dev Find the insert position for a new node with the given NICR
* @param _NICR Node's NICR
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function findInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (address, address) {
return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
// `prevId` does not exist anymore or now has a smaller NICR than the given NICR
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
// `nextId` does not exist anymore or now has a larger NICR than the given NICR
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
// No hint - descend list starting from head
return _descendList(_troveManager, _NICR, data.head);
} else if (prevId == address(0)) {
// No `prevId` for hint - ascend list starting from `nextId`
return _ascendList(_troveManager, _NICR, nextId);
} else if (nextId == address(0)) {
// No `nextId` for hint - descend list starting from `prevId`
return _descendList(_troveManager, _NICR, prevId);
} else {
// Descend list starting from `prevId`
return _descendList(_troveManager, _NICR, prevId);
}
}
// --- 'require' functions ---
function _requireCallerIsTroveManager() internal view {
require(msg.sender == address(troveManager), "SortedTroves: Caller is not the TroveManager");
}
function _requireCallerIsBOorTroveM(ITroveManager _troveManager) internal view {
require(msg.sender == borrowerOperationsAddress || msg.sender == address(_troveManager),
"SortedTroves: Caller is neither BO nor TroveM");
}
}
| A sorted doubly linked list with nodes sorted in descending order. Nodes map to active Troves in the system - the ID property is the address of a Trove owner. Nodes are ordered according to their current nominal individual collateral ratio (NICR), which is like the ICR but without the price, i.e., just collateral / debt. The list optionally accepts insert position hints. NICRs are computed dynamically at runtime, and not stored on the Node. This is because NICRs of active Troves change dynamically as liquidation events occur. The list relies on the fact that liquidation events preserve ordering: a liquidation decreases the NICRs of all active Troves, but maintains their order. A node inserted based on current NICR will maintain the correct position, relative to it's peers, as rewards accumulate, as long as it's raw collateral and debt have not changed. Thus, Nodes remain sorted by current NICR. Nodes need only be re-inserted upon a Trove operation - when the owner adds or removes collateral or debt to their position. The list is a modification of the following audited SortedDoublyLinkedList: Changes made in the Liquity implementation: - Keys have been removed from nodes - Ordering checks for insertion are performed by comparing an NICR argument to the current NICR, calculated at runtime. The list relies on the property that ordering by ICR is maintained as the ETH:USD price varies. - Public functions with parameters have been made internal to save gas, and given an external wrapper function for external access/ Information for a node in the list | contract SortedTroves is Ownable, CheckContract, ISortedTroves {
using SafeMath for uint256;
string constant public NAME = "SortedTroves";
event TroveManagerAddressChanged(address _troveManagerAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
address public borrowerOperationsAddress;
ITroveManager public troveManager;
struct Node {
bool exists;
}
struct Data {
}
Data public data;
function setParams(uint256 _size, address _troveManagerAddress, address _borrowerOperationsAddress) external override onlyOwner {
require(_size > 0, "SortedTroves: Size can’t be zero");
checkContract(_troveManagerAddress);
checkContract(_borrowerOperationsAddress);
data.maxSize = _size;
troveManager = ITroveManager(_troveManagerAddress);
borrowerOperationsAddress = _borrowerOperationsAddress;
emit TroveManagerAddressChanged(_troveManagerAddress);
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
_renounceOwnership();
}
function insert (address _id, uint256 _NICR, address _prevId, address _nextId) external override {
ITroveManager troveManagerCached = troveManager;
_requireCallerIsBOorTroveM(troveManagerCached);
_insert(troveManagerCached, _id, _NICR, _prevId, _nextId);
}
function _insert(ITroveManager _troveManager, address _id, uint256 _NICR, address _prevId, address _nextId) internal {
require(!isFull(), "SortedTroves: List is full");
require(!contains(_id), "SortedTroves: List already contains the node");
require(_id != address(0), "SortedTroves: Id cannot be zero");
require(_NICR > 0, "SortedTroves: NICR must be positive");
address prevId = _prevId;
address nextId = _nextId;
if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
(prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);
}
data.nodes[_id].exists = true;
if (prevId == address(0) && nextId == address(0)) {
data.head = _id;
data.tail = _id;
data.nodes[_id].nextId = data.head;
data.nodes[data.head].prevId = _id;
data.head = _id;
data.nodes[_id].prevId = data.tail;
data.nodes[data.tail].nextId = _id;
data.tail = _id;
data.nodes[_id].nextId = nextId;
data.nodes[_id].prevId = prevId;
data.nodes[prevId].nextId = _id;
data.nodes[nextId].prevId = _id;
}
data.size = data.size.add(1);
emit NodeAdded(_id, _NICR);
}
function _insert(ITroveManager _troveManager, address _id, uint256 _NICR, address _prevId, address _nextId) internal {
require(!isFull(), "SortedTroves: List is full");
require(!contains(_id), "SortedTroves: List already contains the node");
require(_id != address(0), "SortedTroves: Id cannot be zero");
require(_NICR > 0, "SortedTroves: NICR must be positive");
address prevId = _prevId;
address nextId = _nextId;
if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
(prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);
}
data.nodes[_id].exists = true;
if (prevId == address(0) && nextId == address(0)) {
data.head = _id;
data.tail = _id;
data.nodes[_id].nextId = data.head;
data.nodes[data.head].prevId = _id;
data.head = _id;
data.nodes[_id].prevId = data.tail;
data.nodes[data.tail].nextId = _id;
data.tail = _id;
data.nodes[_id].nextId = nextId;
data.nodes[_id].prevId = prevId;
data.nodes[prevId].nextId = _id;
data.nodes[nextId].prevId = _id;
}
data.size = data.size.add(1);
emit NodeAdded(_id, _NICR);
}
function _insert(ITroveManager _troveManager, address _id, uint256 _NICR, address _prevId, address _nextId) internal {
require(!isFull(), "SortedTroves: List is full");
require(!contains(_id), "SortedTroves: List already contains the node");
require(_id != address(0), "SortedTroves: Id cannot be zero");
require(_NICR > 0, "SortedTroves: NICR must be positive");
address prevId = _prevId;
address nextId = _nextId;
if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
(prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);
}
data.nodes[_id].exists = true;
if (prevId == address(0) && nextId == address(0)) {
data.head = _id;
data.tail = _id;
data.nodes[_id].nextId = data.head;
data.nodes[data.head].prevId = _id;
data.head = _id;
data.nodes[_id].prevId = data.tail;
data.nodes[data.tail].nextId = _id;
data.tail = _id;
data.nodes[_id].nextId = nextId;
data.nodes[_id].prevId = prevId;
data.nodes[prevId].nextId = _id;
data.nodes[nextId].prevId = _id;
}
data.size = data.size.add(1);
emit NodeAdded(_id, _NICR);
}
} else if (prevId == address(0)) {
} else if (nextId == address(0)) {
} else {
function remove(address _id) external override {
_requireCallerIsTroveManager();
_remove(_id);
}
function _remove(address _id) internal {
require(contains(_id), "SortedTroves: List does not contain the id");
if (data.size > 1) {
if (_id == data.head) {
data.head = data.nodes[_id].nextId;
data.nodes[data.head].prevId = address(0);
data.tail = data.nodes[_id].prevId;
data.nodes[data.tail].nextId = address(0);
data.nodes[data.nodes[_id].prevId].nextId = data.nodes[_id].nextId;
data.nodes[data.nodes[_id].nextId].prevId = data.nodes[_id].prevId;
}
data.tail = address(0);
}
delete data.nodes[_id];
data.size = data.size.sub(1);
NodeRemoved(_id);
}
function _remove(address _id) internal {
require(contains(_id), "SortedTroves: List does not contain the id");
if (data.size > 1) {
if (_id == data.head) {
data.head = data.nodes[_id].nextId;
data.nodes[data.head].prevId = address(0);
data.tail = data.nodes[_id].prevId;
data.nodes[data.tail].nextId = address(0);
data.nodes[data.nodes[_id].prevId].nextId = data.nodes[_id].nextId;
data.nodes[data.nodes[_id].nextId].prevId = data.nodes[_id].prevId;
}
data.tail = address(0);
}
delete data.nodes[_id];
data.size = data.size.sub(1);
NodeRemoved(_id);
}
function _remove(address _id) internal {
require(contains(_id), "SortedTroves: List does not contain the id");
if (data.size > 1) {
if (_id == data.head) {
data.head = data.nodes[_id].nextId;
data.nodes[data.head].prevId = address(0);
data.tail = data.nodes[_id].prevId;
data.nodes[data.tail].nextId = address(0);
data.nodes[data.nodes[_id].prevId].nextId = data.nodes[_id].nextId;
data.nodes[data.nodes[_id].nextId].prevId = data.nodes[_id].prevId;
}
data.tail = address(0);
}
delete data.nodes[_id];
data.size = data.size.sub(1);
NodeRemoved(_id);
}
} else if (_id == data.tail) {
} else {
} else {
data.head = address(0);
function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external override {
ITroveManager troveManagerCached = troveManager;
_requireCallerIsBOorTroveM(troveManagerCached);
require(contains(_id), "SortedTroves: List does not contain the id");
require(_newNICR > 0, "SortedTroves: NICR must be positive");
_remove(_id);
_insert(troveManagerCached, _id, _newNICR, _prevId, _nextId);
}
function contains(address _id) public view override returns (bool) {
return data.nodes[_id].exists;
}
function isFull() public view override returns (bool) {
return data.size == data.maxSize;
}
function isEmpty() public view override returns (bool) {
return data.size == 0;
}
function getSize() external view override returns (uint256) {
return data.size;
}
function getMaxSize() external view override returns (uint256) {
return data.maxSize;
}
function getFirst() external view override returns (address) {
return data.head;
}
function getLast() external view override returns (address) {
return data.tail;
}
function getNext(address _id) external view override returns (address) {
return data.nodes[_id].nextId;
}
function getPrev(address _id) external view override returns (address) {
return data.nodes[_id].prevId;
}
function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (bool) {
return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);
}
function _validInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (bool) {
if (_prevId == address(0) && _nextId == address(0)) {
return isEmpty();
return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);
return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);
return data.nodes[_prevId].nextId == _nextId &&
_troveManager.getNominalICR(_prevId) >= _NICR &&
_NICR >= _troveManager.getNominalICR(_nextId);
}
}
function _validInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (bool) {
if (_prevId == address(0) && _nextId == address(0)) {
return isEmpty();
return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);
return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);
return data.nodes[_prevId].nextId == _nextId &&
_troveManager.getNominalICR(_prevId) >= _NICR &&
_NICR >= _troveManager.getNominalICR(_nextId);
}
}
} else if (_prevId == address(0)) {
} else if (_nextId == address(0)) {
} else {
function _descendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {
return (address(0), _startId);
}
address prevId = _startId;
address nextId = data.nodes[prevId].nextId;
while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
prevId = data.nodes[prevId].nextId;
nextId = data.nodes[prevId].nextId;
}
return (prevId, nextId);
}
function _descendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {
return (address(0), _startId);
}
address prevId = _startId;
address nextId = data.nodes[prevId].nextId;
while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
prevId = data.nodes[prevId].nextId;
nextId = data.nodes[prevId].nextId;
}
return (prevId, nextId);
}
function _descendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {
return (address(0), _startId);
}
address prevId = _startId;
address nextId = data.nodes[prevId].nextId;
while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
prevId = data.nodes[prevId].nextId;
nextId = data.nodes[prevId].nextId;
}
return (prevId, nextId);
}
function _ascendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = data.nodes[nextId].prevId;
while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
nextId = data.nodes[nextId].prevId;
prevId = data.nodes[nextId].prevId;
}
return (prevId, nextId);
}
function _ascendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = data.nodes[nextId].prevId;
while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
nextId = data.nodes[nextId].prevId;
prevId = data.nodes[nextId].prevId;
}
return (prevId, nextId);
}
function _ascendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = data.nodes[nextId].prevId;
while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
nextId = data.nodes[nextId].prevId;
prevId = data.nodes[nextId].prevId;
}
return (prevId, nextId);
}
function findInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (address, address) {
return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
return _descendList(_troveManager, _NICR, data.head);
return _ascendList(_troveManager, _NICR, nextId);
return _descendList(_troveManager, _NICR, prevId);
return _descendList(_troveManager, _NICR, prevId);
}
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
return _descendList(_troveManager, _NICR, data.head);
return _ascendList(_troveManager, _NICR, nextId);
return _descendList(_troveManager, _NICR, prevId);
return _descendList(_troveManager, _NICR, prevId);
}
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
return _descendList(_troveManager, _NICR, data.head);
return _ascendList(_troveManager, _NICR, nextId);
return _descendList(_troveManager, _NICR, prevId);
return _descendList(_troveManager, _NICR, prevId);
}
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
return _descendList(_troveManager, _NICR, data.head);
return _ascendList(_troveManager, _NICR, nextId);
return _descendList(_troveManager, _NICR, prevId);
return _descendList(_troveManager, _NICR, prevId);
}
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
return _descendList(_troveManager, _NICR, data.head);
return _ascendList(_troveManager, _NICR, nextId);
return _descendList(_troveManager, _NICR, prevId);
return _descendList(_troveManager, _NICR, prevId);
}
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
return _descendList(_troveManager, _NICR, data.head);
return _ascendList(_troveManager, _NICR, nextId);
return _descendList(_troveManager, _NICR, prevId);
return _descendList(_troveManager, _NICR, prevId);
}
}
} else if (prevId == address(0)) {
} else if (nextId == address(0)) {
} else {
function _requireCallerIsTroveManager() internal view {
require(msg.sender == address(troveManager), "SortedTroves: Caller is not the TroveManager");
}
function _requireCallerIsBOorTroveM(ITroveManager _troveManager) internal view {
require(msg.sender == borrowerOperationsAddress || msg.sender == address(_troveManager),
"SortedTroves: Caller is neither BO nor TroveM");
}
}
| 950,727 | [
1,
37,
3115,
741,
440,
93,
8459,
666,
598,
2199,
3115,
316,
17044,
1353,
18,
14037,
852,
358,
2695,
399,
303,
3324,
316,
326,
2619,
300,
326,
1599,
1272,
353,
326,
1758,
434,
279,
399,
303,
537,
3410,
18,
14037,
854,
5901,
4888,
358,
3675,
783,
12457,
1490,
7327,
4508,
2045,
287,
7169,
261,
31883,
54,
3631,
1492,
353,
3007,
326,
467,
5093,
1496,
2887,
326,
6205,
16,
277,
18,
73,
12990,
2537,
4508,
2045,
287,
342,
18202,
88,
18,
1021,
666,
8771,
8104,
2243,
1754,
13442,
18,
423,
2871,
18880,
854,
8470,
18373,
622,
3099,
16,
471,
486,
4041,
603,
326,
2029,
18,
1220,
353,
2724,
423,
2871,
18880,
434,
2695,
399,
303,
3324,
2549,
18373,
487,
4501,
26595,
367,
2641,
3334,
18,
1021,
666,
14719,
281,
603,
326,
5410,
716,
4501,
26595,
367,
2641,
9420,
9543,
30,
279,
4501,
26595,
367,
23850,
3304,
326,
423,
2871,
18880,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
13717,
56,
303,
3324,
353,
14223,
6914,
16,
2073,
8924,
16,
467,
11739,
56,
303,
3324,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
5381,
1071,
6048,
273,
315,
11739,
56,
303,
3324,
14432,
203,
203,
565,
871,
399,
303,
537,
1318,
1887,
5033,
12,
2867,
389,
88,
303,
537,
1318,
1887,
1769,
203,
565,
871,
605,
15318,
264,
9343,
1887,
5033,
12,
2867,
389,
70,
15318,
264,
9343,
1887,
1769,
203,
565,
871,
2029,
8602,
12,
2867,
389,
350,
16,
2254,
389,
31883,
54,
1769,
203,
565,
871,
2029,
10026,
12,
2867,
389,
350,
1769,
203,
203,
565,
1758,
1071,
29759,
264,
9343,
1887,
31,
203,
203,
565,
24142,
303,
537,
1318,
1071,
23432,
537,
1318,
31,
203,
203,
203,
565,
1958,
2029,
288,
203,
3639,
1426,
1704,
31,
203,
565,
289,
203,
203,
565,
1958,
1910,
288,
203,
565,
289,
203,
203,
565,
1910,
1071,
501,
31,
203,
203,
203,
565,
445,
31705,
12,
11890,
5034,
389,
1467,
16,
1758,
389,
88,
303,
537,
1318,
1887,
16,
1758,
389,
70,
15318,
264,
9343,
1887,
13,
3903,
3849,
1338,
5541,
288,
203,
3639,
2583,
24899,
1467,
405,
374,
16,
315,
11739,
56,
303,
3324,
30,
6321,
848,
163,
227,
252,
88,
506,
3634,
8863,
203,
3639,
866,
8924,
24899,
88,
303,
537,
1318,
1887,
1769,
203,
3639,
866,
8924,
24899,
70,
15318,
264,
9343,
1887,
1769,
203,
203,
3639,
501,
18,
1896,
1225,
273,
389,
1467,
31,
203,
203,
3639,
23432,
537,
1318,
273,
24142,
303,
2
]
|
./partial_match/1/0x5C5293EabBC96a62788b4CA0D393042D4e931e81/sources/src/interfaces/IAction.sol | * @notice Used when trying to set an invalid action for a smart vault. @param address_ Address of the invalid action./ | error InvalidAction(address address_);
| 4,413,419 | [
1,
6668,
1347,
8374,
358,
444,
392,
2057,
1301,
364,
279,
13706,
9229,
18,
225,
1758,
67,
5267,
434,
326,
2057,
1301,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1636,
1962,
1803,
12,
2867,
1758,
67,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity
*/
contract StandardToken is ERC20 {
using SafeMath for uint256;
uint256 internal _totalSupply;
mapping(address => uint256) internal _balanceOf;
mapping (address => mapping (address => uint256)) internal _allowance;
modifier onlyValidAddress(address addr) {
require(addr != address(0), "Address cannot be zero");
_;
}
modifier onlySufficientBalance(address from, uint256 value) {
require(value <= _balanceOf[from], "Insufficient balance");
_;
}
modifier onlySufficientAllowance(address owner, address spender, uint256 value) {
require(value <= _allowance[owner][spender], "Insufficient allowance");
_;
}
/**
* @dev Transfers token to the specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value)
public
onlyValidAddress(to)
onlySufficientBalance(msg.sender, value)
returns (bool)
{
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(value);
_balanceOf[to] = _balanceOf[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Transfers 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
onlyValidAddress(to)
onlySufficientBalance(from, value)
onlySufficientAllowance(from, msg.sender, value)
returns (bool)
{
_balanceOf[from] = _balanceOf[from].sub(value);
_balanceOf[to] = _balanceOf[to].add(value);
_allowance[from][msg.sender] = _allowance[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approves 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
onlyValidAddress(spender)
returns (bool)
{
_allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increases the amount of tokens that an owner allowed to a spender.
*
* approve should be called when _allowance[spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @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
onlyValidAddress(spender)
returns (bool)
{
_allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @dev Decreases the amount of tokens that an owner allowed to a spender.
*
* approve should be called when _allowance[spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @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
onlyValidAddress(spender)
onlySufficientAllowance(msg.sender, spender, subtractedValue)
returns (bool)
{
_allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @dev Gets 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 _balanceOf[owner];
}
/**
* @dev Checks 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 _allowance[owner][spender];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* @dev Based on https://github.com/OpenZeppelin/zeppelin-soliditysettable
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner, "Can only be called by the owner");
_;
}
modifier onlyValidAddress(address addr) {
require(addr != address(0), "Address cannot be zero");
_;
}
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @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
onlyValidAddress(newOwner)
{
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Standard token with minting
* @dev Based on https://github.com/OpenZeppelin/zeppelin-solidity
*/
contract MintableToken is StandardToken, Ownable {
uint256 public cap;
modifier onlyNotExceedingCap(uint256 amount) {
require(_totalSupply.add(amount) <= cap, "Total supply must not exceed cap");
_;
}
constructor(uint256 _cap) public {
cap = _cap;
}
/**
* @dev Creates new tokens for the given address
* @param to The address that will receive the minted tokens.
* @param amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 amount)
public
onlyOwner
onlyValidAddress(to)
onlyNotExceedingCap(amount)
returns (bool)
{
_mint(to, amount);
return true;
}
/**
* @dev Creates new tokens for the given addresses
* @param addresses The array of addresses that will receive the minted tokens.
* @param amounts The array of amounts of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mintMany(address[] addresses, uint256[] amounts)
public
onlyOwner
onlyNotExceedingCap(_sum(amounts))
returns (bool)
{
require(
addresses.length == amounts.length,
"Addresses array must be the same size as amounts array"
);
for (uint256 i = 0; i < addresses.length; i++) {
_mint(addresses[i], amounts[i]);
}
return true;
}
function _mint(address to, uint256 amount)
internal
onlyValidAddress(to)
{
_totalSupply = _totalSupply.add(amount);
_balanceOf[to] = _balanceOf[to].add(amount);
emit Transfer(address(0), to, amount);
}
function _sum(uint256[] arr) internal pure returns (uint256) {
uint256 aggr = 0;
for (uint256 i = 0; i < arr.length; i++) {
aggr = aggr.add(arr[i]);
}
return aggr;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
/**
* @dev Burns a specific amount of tokens.
* @param amount The amount of token to be burned.
*/
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from The account whose tokens will be burnt.
* @param amount The amount of token that will be burnt.
*/
function burnFrom(address from, uint256 amount)
public
onlyValidAddress(from)
onlySufficientAllowance(from, msg.sender, amount)
{
_allowance[from][msg.sender] = _allowance[from][msg.sender].sub(amount);
_burn(from, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param from The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address from, uint256 amount)
internal
onlySufficientBalance(from, amount)
{
_totalSupply = _totalSupply.sub(amount);
_balanceOf[from] = _balanceOf[from].sub(amount);
emit Transfer(from, address(0), amount);
}
}
contract TradeTokenX is MintableToken, BurnableToken {
string public name = "Trade Token X";
string public symbol = "TIOx";
uint8 public decimals = 18;
uint256 public cap = 223534822661022743815939072;
// solhint-disable-next-line no-empty-blocks
constructor() public MintableToken(cap) {}
} | * @title Burnable Token @dev Token that can be irreversibly burned (destroyed)./ | contract BurnableToken is StandardToken {
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
function burnFrom(address from, uint256 amount)
public
onlyValidAddress(from)
onlySufficientAllowance(from, msg.sender, amount)
{
_allowance[from][msg.sender] = _allowance[from][msg.sender].sub(amount);
_burn(from, amount);
}
function _burn(address from, uint256 amount)
internal
onlySufficientBalance(from, amount)
{
_totalSupply = _totalSupply.sub(amount);
_balanceOf[from] = _balanceOf[from].sub(amount);
emit Transfer(from, address(0), amount);
}
}
| 12,735,901 | [
1,
38,
321,
429,
3155,
225,
3155,
716,
848,
506,
9482,
266,
2496,
24755,
18305,
329,
261,
11662,
329,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
605,
321,
429,
1345,
353,
8263,
1345,
288,
203,
565,
445,
18305,
12,
11890,
5034,
3844,
13,
1071,
288,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
1265,
12,
2867,
628,
16,
2254,
5034,
3844,
13,
203,
3639,
1071,
203,
3639,
1338,
1556,
1887,
12,
2080,
13,
203,
3639,
1338,
55,
11339,
7009,
1359,
12,
2080,
16,
1234,
18,
15330,
16,
3844,
13,
203,
565,
288,
203,
3639,
389,
5965,
1359,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
389,
5965,
1359,
63,
2080,
6362,
3576,
18,
15330,
8009,
1717,
12,
8949,
1769,
203,
203,
3639,
389,
70,
321,
12,
2080,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
70,
321,
12,
2867,
628,
16,
2254,
5034,
3844,
13,
203,
3639,
2713,
203,
3639,
1338,
55,
11339,
13937,
12,
2080,
16,
3844,
13,
203,
565,
288,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1717,
12,
8949,
1769,
203,
3639,
389,
12296,
951,
63,
2080,
65,
273,
389,
12296,
951,
63,
2080,
8009,
1717,
12,
8949,
1769,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* (0x%x,2909) Solo une altro contratta che ho fatto. Nel codice ci fidiame. In crito e rifugio. Crito-difese à vita.
*
* Author: 2021 Crypto Fix Finance and Contributors. BSD 3-Clause Licensed.
* Baseate ni Putanas.
* Passed compliance checks by 0xFF4 marked XFC.
* Final version: need to change router and wallet_xxx only.
* v0.4 flex tax, moved Best Common Practice functions to inc/OZBCP.sol to somewhere else.
* v0.4.3 brought some initial cryptopanarchy elements, fixed bugs and run unit tests.
* v0.4.4 starting to incorporate some properties from my crypto-panarchy model: (f0.1) health, natural disaster, commercial
* engagements with particular contract signature, fine, trust chain and finally private arbitration.
* v0.5.1 implemented several crypto-panarchy elements into this contract, fully tested so far.
* v0.5.2 coded private court arbitration under policentric law model inspired by Tracanelli-Bell prov arbitration model
* v0.5.3 added hash based signature to private agreements
* v0.5.4 wdAgreement implemented, however EVM contract size is too large, reduced optimizations run as low as 50
* v0.5.5 refactored contract due to size limit (added a library, merged functions, converted public, shortened err messages, etc)
* v0.5.6 VolNI & DAO as external contracts interacting with main contract due to contract size and proper architecture
*
* XXXTODO (Feature List F#):
* - {DONE} (f1) taxationMechanisms: HOA-like, convenant community (Hoppe), Tax=Theft (Rothbard), Voluntary Taxation (Objectivism)
* - {DONE} (f2) reflection mechanism
* - {DONE} (f3) Burn/LP/Reward mechanisms comon to tokens on the surface
* - {DONE} (f4) contract management: ownership transfer, resignation; contract lock/unlock, routerUpdate
* - (f5) DAO: contractUpgrade, transfer ownership to DAO contract for management
* - {DONE} (f6) criar um mecanismo que cobra taxa apenas de transacoes na pool, taxa sobre servico nao circulacao.
* - {DONE} (f7) v5.1 add auto health wallet (wallet_health) and private SailBoat insurance (wallet_sailboat||wallet_health)
* - {DONE} (f8) account individual contributors to health wallet.
* - {DONE} (f9) arbitrated contract mechanism setAgreement(hashDoc,multa,arbitragemScheme,tribunalPrivado,wallet_juiz,assinatura,etc)
* - (f10) mechanism for NI (negative income) (maybe import from Seasteading Bahamas Denizens (SeaBSD)
* - {DONE} (f11) v5.1 [trustChain] implement 0xff4 trust chain model (DEFCON-like): trust ontology cardinality 1:N:M
* - {DONE} (f12) v5.1 [trustChain] firstTrustee, trustPoints[avg,qty], whoYouTrust, whoTrustYou, contractsViolated, optOutArbitrations(max:1)
* - {DONE} (f13) v5.1 [trustChain] nickName, pgpPubK, sshPubK, x509pubK, Gecos field, Role field
* - {DONE} (f14) v5.1 [trustChain] if you send 0,57721566 tokens to someone and nobody trusted this person before, you become their spFirstTrusteer
* - {DONE} (f15) add mechanism to pool negotiation with trustedPersona only
* - {DONE} (f16) add generic escrow mechanism allowing the private arbitration (admin) on the trust chain [trustChain]
*
* Before you deploy:
* - Change CONFIG:hardcoded definitions according to this crypto-panarchy immutable terms.
* - Change wallet_health initial address.
* - Security Audit is done everywhere its noted
**/
pragma solidity ^0.8.7;
// SPDX-License-Identifier: BSD 3-Clause Licensed.
//Author: (0x%x,2909) Crypto Fix Finance
// Declara interfaces do ERC20/BEP20/SEP20 importa BCP do OZ e tbm interfaces e metodos da DeFi
import "inc/OZBCP.sol";
import "inc/DEFI.sol";
import "inc/LIBXFFA.sol";
contract XFFAv5 is Context, IERC20, Ownable {
using SafeMath for uint256; // no reason to keep using SafeMath on solic >= 0.8.x
using Address for address;
// Algumas propriedades particulares ao self=(msg.sender) e selfPersona (how self is seem or presents himself)
struct selfProperties {
string sNickname; // name yourself if/how you want: avatar, nick, alias, PGP key, x-persona
uint256 sTaxFee;
uint256 sLiquidityFee;
uint256 sHealthFee; // health insurance fee (f0.1)
// finger
string sPgpPubK;
string sSshPubK;
string sX509PubK;
string sGecos; // Unix generic commentaries field
// trustChain
address spFirstTrustee;
address[] sYouTrust;
address[] spTrustYou;
uint256[2] spTrustPoints; // count,points
uint256 spContractsViolated; // only the contract will set this
uint256 spOptOutArbitrations; // only arbitrators should set this
address[] ostracizedBy; // court or judge
uint256 sRole; // 0=user, 1=judge/court/arbitrator
// private agreements
uint256[] spYouAgreementsSigned;
}
struct subContractProperties {
string hash;
string gecos; // generic comments describing the contract
string url; // ipfs, https, etc
uint256 fine;
uint256 deposit; // uint instead of bool to save gwei, 1 = required
address creator;
uint256 createdOn;
address arbitrator; // private court or selected judge
uint256 arbitratorFee; // in tokens
mapping (address => uint256) signedOn; // signees and timestamp
mapping (address => string) signedHash;
mapping (address => string) signComment;
mapping (address => bytes32) signature;
mapping (address => uint256) signatureNonce;
mapping (address => uint256) finePaid; // bool->uint to save gas
mapping (address => uint256) state; // 1=active/signed, 2=want_friendly_terminate, 3=want_dispute, 4=won_dispute, 5=lost_dispute, 21=friendly_withdrawaled, 41=disputed_wdled, 91=arbitrator_wdled 99=disputed_outside(ostracized)
address[] signees; // list of who signed this contract
}
mapping (address => selfProperties) private _selfDetermined;
mapping (uint256 => subContractProperties) private _privLawAgreement;
uint256[] public _privLawAgreementIDs;
//OLD version mapping (address => mapping (address => uint256)) private _selfDeterminedFees;// = [_taxFee, _liquidityFee, _healthFee];
// _rOwned e _tOwned melhores praticas do SM (conformidade com OpenZeppelin tbm)
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedF; // marca essa flag na wallet que nao paga fee
mapping (address => bool) private _isExcludedR; // marca essa flag na wallet que nao recebe dividendos
address[] private _excluded;
address private wallet_health = 0x8c348A2a5Fd4a98EaFD017a66930f36385F3263A; //owner(); // Mudar para wallet health
mapping (address => uint256) public healthDepositTracker; // (f8) track who deposits to bealth
uint8 private constant _decimals = 8; // Auditoria XFC-05: constante
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 29092909 * 10**_decimals; // 2909 2909 milhoes Auditoria XFC-05: constante + decimals precisao cientifica pq das matematicas zoadas do sol
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "Coin 0xFF4"; // Auditoria XFC-05: constante
string private constant _symbol = "XFFA"; //Auditoria XFC-05: constante
uint256 private _maxTassazione = 8; // tassazione massima, hello Trieste Friulane (CONFIG:hardcoded)
uint256 private _taxFee = 1; // taxa pra dividendos
uint256 private _previousTaxFee = _taxFee; // inicializa
uint256 private _liquidityFee = 1; // taxa pra LP
uint256 private _previousLiquidityFee = _liquidityFee; // inicializa
uint256 private _burnFee = 1; // taxa de burn (deflacao) por operacao estrategia de deflacao continua (f3)
uint256 private _previousBurnFee = _burnFee; // inicializa (f3)
uint256 private _healthFee = 1; // Em porcentagem, fee direto pra health
uint256 private _prevHealthFee = _healthFee; // Em porcentagem, fee direto pra health
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify; // liga e desliga o mecanismo de liquidez
bool private swapAndLiquifyEnabled = false; // inicializa
uint256 private _maxTxAmount = 290900 * 10**_decimals; // mandei 290.9k max transfer que da 1% do supply inicial (nao do circulante, logo isso muda com o tempo)
uint256 private numTokensSellToAddToLiquidity = 2909 * 10**_decimals; // 2909 minimo de tokens pra adicionar na LP se estiver abaixo
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled); // liga
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
event AuthZ(uint256 _reason);
modifier travaSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
/**
* spOptOutArbitrations means a private law Court or selected arbitrator associated to a secondary
* contract was ruled out because the party opted out exterritorial private crypto-panarchy society
* going back to nation-state rule of law which is an explicity opt-out from our crypto-panarchy.
* Maybe the ostracized x-persona invoked other arbitration mechanism outside this main contract
* or outside the secondary contract terms. Usually it's less radical, therefore the ruling courts
* should be asked. Court/judge address() is identifiable when it happens. This persona shall be
* ostracized, boycotted or even physically removed from all states of affair related to this
* contract. If by any means he is accepted back, should be another address as this operation is
* not reversible.
*
**/
modifier notPhysicallyRemoved() {
_notPhysicallyRemoved();
_;
}
function _notPhysicallyRemoved() internal view {
require(_selfDetermined[_msgSender()].spOptOutArbitrations < 1, "A2: ostracized"); // ostracized
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
//IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // PRD
//IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x928Add24A9dd3E76e72aD608c91C2E3b65907cdD); // Address for DeFi at Kooderit (FIX)
//IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1); // BSC Testnet
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7186Fe885Db3402102250bD3d79b7914c61414b1); // CryptoFIX Finance (FreeBSD)
// Cria o parzinho Token/COIN pra swap e recebe endereco
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
//uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), address(0x465e07d6028830124BE2E4aA551fBe12805dB0f5)); // Wrapped XMR (Monero)
// recebe as outras variaveis do contrato via IUniswapV2Router02
uniswapV2Router = _uniswapV2Router;
//owner e o proprio contrato nao pagam fee inicialmente
_isExcludedF[owner()] = true;
_isExcludedF[address(this)] = true;
// _isExcludedF[wallet_health] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
// Auditoria XFC-05: view->pure nos 4
function name() public pure returns (string memory) { return _name; }
function symbol() public pure returns (string memory) { return _symbol; }
function decimals() public pure returns (uint256) { return _decimals; }
function totalSupply() public pure override returns (uint256) { return _tTotal; }
// Checa saldo dividendos da conta
function balanceOf(address account) public view override returns(uint256) {
if (_isExcludedR[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]); // (f2)
}
function transfer(address recipient, uint256 amount) public override notPhysicallyRemoved() returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override notPhysicallyRemoved() returns(uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override notPhysicallyRemoved() returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override notPhysicallyRemoved() 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 notPhysicallyRemoved() returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual notPhysicallyRemoved() returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcludedR[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
// XFC-04 Compliance: documentando funcao de saque. used2b reflect() no token reflect
// Implementar na Web3 um mecanismo pra facilitar uso. (f2)
function wdSaque(uint256 tQuantia) public notPhysicallyRemoved() {
address remetente = _msgSender();
require(!_isExcludedR[remetente], "A2: ur excluded"); // Excluded address can not call this function
(uint256 rAmount,,,,,) = _getValues(tQuantia);
_rOwned[remetente] = _rOwned[remetente].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tQuantia);
}
// To calculate the token count much more precisely, you convert the token amount into another unit.
// This is done in this helper function: "reflectionFromToken()". Code came from Reflect Finance project. (f2)
function reflectionFromToken(uint256 tQuantia, bool deductTransferFee) public view returns(uint256) {
require(tQuantia <= _tTotal, "E:Amount > supply"); // Amount must be less than supply"
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tQuantia);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tQuantia);
return rTransferAmount;
}
}
// Inverse operation. (f2)
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "E:Amount > reflections total"); // Amount must be less than total reflections
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excluiReward(address account) public onlyOwner() {
require(!_isExcludedR[account], "Already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]); // (f2)
}
_isExcludedR[account] = true;
_excluded.push(account);
}
function incluiReward(address account) external onlyOwner() {
require(_isExcludedR[account], "Not excluded"); // Auditoria XFC-06 Account is not excluded
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcludedR[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tQuantia) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia);
_tOwned[sender] = _tOwned[sender].sub(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2)
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner { _isExcludedF[account] = true; }
function includeInFee(address account) public onlyOwner { _isExcludedF[account] = false; }
// Permite redefinir taxa maxima de transfer, assume compromisso hardcoded de sempre ser menor que 8% (convenant community rules)
function setBurnFeePercent(uint256 burnFee) external onlyOwner() { _burnFee = burnFee; } // burn nao e tax (f3)
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
require((taxFee+_liquidityFee+_healthFee)<=_maxTassazione,"Taxation is Theft"); // Taxation without representation is Theft
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
require((liquidityFee+_taxFee+_healthFee)<=_maxTassazione,"Taxation is Theft");
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent <= 8,"Taxation wo representation is Theft");
_maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); // Regra de 3 pra porcentagem
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//recebe XMR/ETH/BNB/BCH do uniswapV2Router quando fizer swap - Auditoria: XFC-07
receive() external payable {}
// subtrai rTotal e soma fee no fee tFeeTotal (f2)
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
// From SM/OZ
function _getValues(uint256 tQuantia) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tQuantia);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tQuantia, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
// From SM/OZ
function _getTValues(uint256 tQuantia) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tQuantia);
uint256 tLiquidity = calculateLiquidityFee(tQuantia);
uint256 tTransferAmount = tQuantia.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
// From SM/OZ
function _getRValues(uint256 tQuantia, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tQuantia.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
// From SM/OpenZeppelin
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
// From SM/OpenZeppelin
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
// Recebe liquidity
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcludedR[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2); // regra de 3 pra achar porcentagem
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(10**2); // regra de 3 pra achar porcentagem
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0 && _burnFee == 0) return; //(f3)
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_previousBurnFee = _burnFee;
_prevHealthFee = _healthFee;
_taxFee = 0;
_liquidityFee = 0;
_burnFee = 0;
_healthFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
_burnFee = _previousBurnFee; // (f3)
_healthFee = _prevHealthFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedF[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "E: addr zero?"); // ERC20: approve from the zero address
require(spender != address(0), "E: addr zero?");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer( address from, address to, uint256 amount) private {
require(from != address(0), "E: addr zero?"); // ERC20: transfer from the zero address
require(amount > 0, "Amount too low"); // Transfer amount must be greater than zero
if(from == uniswapV2Pair || to == uniswapV2Pair) // if DeFi, must be trusted (f15), owner is no exception T:OK (CONFIG:hardcoded)
require(_selfDetermined[to].spFirstTrustee!=address(0)||_selfDetermined[from].spFirstTrustee!=address(0),"A2: DeFi limited to trusted. Use p2p"); // (f15) T:OK DeFi service limited to trusted x-persona. Use p2p.
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Amount too high"); // Transfer amount exceeds the maxTxAmount.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
// Se a liquidez do pool estiver muito baixa (numTokensSellToAddToLiquidity) vamos vender
// pra colocar na LP.
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true; // default true
// (f6) dont charge fees on p2p transactions. comment out (CONFIG:hardcoded) if this crypto-panarchy wants different
if (from != uniswapV2Pair && to!= uniswapV2Pair) { takeFee = false; } // maybe make it configurable?
if (to == wallet_health) { healthDepositTracker[from].add(amount); } // (f8,f7) keep track of who contributes more to health funds
//if any account belongs to _isExcludedF account then remove the fee
if(_isExcludedF[from] || _isExcludedF[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private travaSwap {
// split the contract balance into halves - Auditoria XFC-08: points a bug and a need to a withdraw function to get leftovers
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// computa apenas os XMR/ETH/BNB/BCH da transacao, excetuando o que eventualmente ja houver no contrato
uint256 initialBalance = address(this).balance;
// metade do saldo em crypto
swapTokensForEth(half); // <- this breaks the ETH -> TOKEN swap when swap+liquify is triggered
// saldo atual em crypto
uint256 newBalance = address(this).balance.sub(initialBalance);
// segunda metade em token - Auditoria XFC-08: points a bug and a need to a withdraw function to get leftovers
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf); // Referencia: event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// faz o swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount,
0, // aceita qualquer valor de ETH sem minimo
path, address(this), block.timestamp);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity - Auditoria: XFC-09 unhandled
uniswapV2Router.addLiquidityETH{value: ethAmount}(address(this), tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this), // owner(), Auditoria XFC-02
block.timestamp);
}
//metodo das taxas se takeFee for true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
//_healthFee = 1; // Em porcentagem
// modifica o health na origem individualmente
if (_selfDetermined[sender].sHealthFee >= _healthFee || _selfDetermined[sender].sHealthFee == 999 ) {
_healthFee = _selfDetermined[sender].sHealthFee;
if (_selfDetermined[sender].sHealthFee == 999) { _healthFee = 0; } // 999 na blockchain eh 0 para nos
}
uint256 burnAmt = amount.mul(_burnFee).div(100);
uint256 healthAmt = amount.mul(_healthFee).div(100); // N% direto pra health? discutir ou por hora manter 0
uint256 discountAmt=(burnAmt+healthAmt); // sera descontado do total a transferir
/** (note que a unica tx real eh a da health, o resto reverte pra todos e pra saude da pool) **/
// Respeitar fees individuais, precedencia de quem paga (origem): dividendos
if (_selfDetermined[sender].sTaxFee >= _taxFee || _selfDetermined[recipient].sTaxFee >= _taxFee || _selfDetermined[sender].sTaxFee == 999 || _selfDetermined[recipient].sTaxFee == 999) {
if (_selfDetermined[sender].sTaxFee > _selfDetermined[recipient].sTaxFee) {
_taxFee = _selfDetermined[sender].sTaxFee;
if (_selfDetermined[sender].sTaxFee == 999) { _taxFee = 0; }
}
else {
_taxFee = _selfDetermined[recipient].sTaxFee;
if (_selfDetermined[recipient].sTaxFee == 999) { _taxFee = 0; }
}
}
// Respeitar fees individuais, precedencia de quem paga (origem): liquidez
if (_selfDetermined[sender].sLiquidityFee >= _liquidityFee || _selfDetermined[recipient].sLiquidityFee >= _liquidityFee || _selfDetermined[sender].sLiquidityFee == 999 || _selfDetermined[recipient].sLiquidityFee == 999) {
if (_selfDetermined[sender].sLiquidityFee > _selfDetermined[recipient].sLiquidityFee) {
_liquidityFee = _selfDetermined[sender].sLiquidityFee;
if (_selfDetermined[sender].sLiquidityFee == 999) { _liquidityFee = 0; }
}
else {
_liquidityFee = _selfDetermined[recipient].sLiquidityFee;
if (_selfDetermined[recipient].sLiquidityFee == 999) { _liquidityFee = 0; }
}
}
// Taxas considerando exclusao de recompensa
if (_isExcludedR[sender] && !_isExcludedR[recipient]) {
_transferFromExcluded(sender, recipient, amount.sub(discountAmt));
} else if (!_isExcludedR[sender] && _isExcludedR[recipient]) {
_transferToExcluded(sender, recipient, amount.sub(discountAmt));
// XFC-10 excluded } else if (!_isExcludedR[sender] && !_isExcludedR[recipient]) {
// XFC-10 excluded _transferStandard(sender, recipient, amount);
} else if (_isExcludedR[sender] && _isExcludedR[recipient]) {
_transferBothExcluded(sender, recipient, amount.sub(discountAmt));
} else if (!_isExcludedR[sender] && !_isExcludedR[recipient]) {
_transferStandard(sender, recipient, amount.sub(discountAmt)); // XFC-10 condition above added
}
// Depois de feitas as transferencias entre os pares, o proprio contrato nao paga taxas
_taxFee = 0; _liquidityFee = 0; _healthFee = 0;
// sobrou discountAmt precisamos enviar pras carteiras de direito, burn e health
_transferStandard(sender, address(0x000000000000000000000000000000000000dEaD), burnAmt); // envia pro burn 0x0::dEaD a fee configurada sem gambi de burn holder
_transferStandard(sender, address(wallet_health), healthAmt); // (f7) pay fee to health wallet, debate it widely with this panarchy
healthDepositTracker[sender].add(healthAmt); // (f8) keep track of who contributes more to health funds
// Restaura as taxas
_taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _healthFee = _prevHealthFee;
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tQuantia) private {
if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant) T:OK:f14
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee); // (f2)
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tQuantia) private {
if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant)
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee); // (f2)
emit Transfer(sender, recipient, tTransferAmount);
}
function setRouterAddress(address novoRouter) public onlyOwner() {
//Ideia boa do FreezyEx, permite mudar o router da Pancake pra upgrade. Atende tambem compliace XFC-03 controle de. external & 3rd party
IUniswapV2Router02 _newPancakeRouter = IUniswapV2Router02(novoRouter);
uniswapV2Pair = IUniswapV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH());
uniswapV2Router = _newPancakeRouter;
}
function _transferFromExcluded(address sender, address recipient, uint256 tQuantia) private {
if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant)
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia);
_tOwned[sender] = _tOwned[sender].sub(tQuantia);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee); // (f2)
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* "In a fully free society, taxation—or, to be exact, payment for governmental services—would be voluntary.
* Since the proper services of a government—the police, the armed forces, the law courts—are demonstrably needed
* by individual citizens and affect their interests directly, the citizens would (and should) be willing to pay
* for such services, as they pay for insurance.", Virtue of Selfishness (1964) Chapter 15
*
* Verifichiamo allora nella pratica questa irragionevole ipotesi teorica di tassazione volontaria. Chiamiamo la funzione aynRand,
* per consentire al singolo chiamante di sospendere le proprie quote, accettare la quota associativa o impostare la propria
* proprio canone. Bene che metta alla prova anche la benevolenza contro l'altruismo (Auguste Comte 1798-1857) e il consenso su
* Termini del consenso della allianza privata - convenant community (Hans H. Hoppe, diversi scritti).
* // T:OK:(f1)
*/
function aynRandTaxation(uint256 TaxationIsTheft, uint256 convernantCommunityTaxes, uint256 indTaxFee, uint256 indLiquidFee, uint256 indHealthFee) public {
// booleans are expensive, save gas. pass 1 as true to TaxationIsTheft
if (TaxationIsTheft==1) {
excludeFromFee(msg.sender); excluiReward(msg.sender); // sem tax sem dividendos
}
else if ((TaxationIsTheft!=1) && (convernantCommunityTaxes==1)) {
// restoreAllFee() se imposto nao e roubo e Hoppe estava certo (sobre acerto da alianca privada)
_selfDetermined[msg.sender].sHealthFee = _healthFee;
_selfDetermined[msg.sender].sLiquidityFee = _liquidityFee;
_selfDetermined[msg.sender].sTaxFee = _taxFee;
//_individualFee = [_taxFee, _liquidityFee, _healthFee];
} else {
// define os 'impostos voluntarios' auto determinados
if (indHealthFee==0) indHealthFee=999; if (indLiquidFee==0) indLiquidFee=999; if (indTaxFee==0) indTaxFee=999; // pra economizar gas nao vamos testar booleano se variavel foi inicializada entao consideraremos 0% com o valor especial 999
_selfDetermined[msg.sender].sHealthFee = indHealthFee;
_selfDetermined[msg.sender].sLiquidityFee = indLiquidFee;
_selfDetermined[msg.sender].sTaxFee = indTaxFee;
//_individualFee = [indTaxFee, indLiquidFee, indHealthFee];
}
}
// T:OK:(f0.1)
function setHealthWallet(address newHealthAddr) public onlyOwner() returns(bool) {
wallet_health = newHealthAddr;
return true;
}
// T:OK:(f1):default fees and caller fees
function getFees() public view returns(uint256,uint256,uint256,uint256,uint256,uint256) {
return (_healthFee,_liquidityFee,_taxFee,_selfDetermined[msg.sender].sHealthFee,_selfDetermined[msg.sender].sLiquidityFee,_selfDetermined[msg.sender].sTaxFee);
}
// T:OK (f13): nickname handling merged to finger to save gas and contract size
// T:OK (f13): refactorado per l'uso require() if (bytes(_selfDetermined[endereco].sNickname).length == 0) return _selfDetermined[endereco].sNickname;
// XXX_Todo: implementar modificador onlyPrivLawCourt caso torne essa funcao publica
// testar notPhysicallyRemoved() (DONE) e setViolations unitariamente
// T:PEND (f12):Dropped this function. Included in setArbitration()
/* function setViolations(uint256 _violationType, address _who) internal notPhysicallyRemoved() returns(uint256 _spContractsViolated) {
require(_violationType>=0&&_violationType<=2,"A2 bad type"); // AuthZ: violation types: 0 (contracts) or 1 (arbitration)
if (_violationType==1) {
// worse case scenario: kicked out out crypto-panarchy
_selfDetermined[_who].spOptOutArbitrations.add(1);
_selfDetermined[_who].ostracizedBy.push(_msgSender());
}
else
_selfDetermined[_who].spContractsViolated.add(1);
return(_selfDetermined[_who].spContractsViolated);
}*/
// T:OK (f12)
function setTrustPoints(address _who, uint256 _points) public notPhysicallyRemoved() {
require((_points >= 0 && _points <= 5),"E: points 0-5"); // AuthZ: points must be 0-5
require(_who!=_msgSender(),"A2: points to self"); // AuthZ: you can't set points to yourself.
_selfDetermined[_who].spTrustPoints = [
_selfDetermined[_who].spTrustPoints[0].add(1), // count++
_selfDetermined[_who].spTrustPoints[1].add(_points) // give points
// Save gas, let the client find the average _selfDetermined[_who].spTrustPoints[2]=_selfDetermined[_who].spTrustPoints[1].div(_selfDetermined[_who].spTrustPoints[0]) // calculates new avg
];
_selfDetermined[_who].spTrustPoints = [
_selfDetermined[_msgSender()].spTrustPoints[0].add(1), // count++
_selfDetermined[_msgSender()].spTrustPoints[1].sub(_points) // subtracts points from giver
];
}
// T:OK (f12):merged to trustchain function getTrustPoints(address _who)
/* function getTrustPoints(address _who) public view returns(uint256[2] memory _currPoints) {
return(_selfDetermined[_who].spTrustPoints);
}*/
/* XXX_Lembrar_de_Remover XXX_implement point system upon contracts or make setTrustPoints public (f12)
function vai(address _who) public {
setTrustPoints(_who,1);
setTrustPoints(_who,2);
setTrustPoints(_who,3);
}
*/
//T:OK (f13)
function setFinger(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) public notPhysicallyRemoved() {
_selfDetermined[_msgSender()].sPgpPubK=_sPgpPubK;
_selfDetermined[_msgSender()].sSshPubK=_sSshPubK;
_selfDetermined[_msgSender()].sX509PubK=_sX509PubK;
_selfDetermined[_msgSender()].sGecos=_sGecos;
_selfDetermined[_msgSender()].sRole=_sRole;
_selfDetermined[_msgSender()].sNickname=_sNickname;
}
// T:OK (f11)
function setWhoUtrust(uint256 mode,address _youTrust) public notPhysicallyRemoved() returns(uint256 _len) {
require(_selfDetermined[_msgSender()].sYouTrust.length < 150,"A2: trustChain too big"); // convenant size limit = (Dunbar's number: 150, Bernard–Killworth median: 231);
if (owner()!=_msgSender()) {
require(_msgSender()!=_youTrust,"A2: no trust self"); // AuthZ: you can't trust yourself
require(_youTrust!=uniswapV2Pair,"A2: no trust pair"); // AuthZ: you can't trust special contracts
}
// mode 1 is to delete from your trust list (you are not a trustee), bool->int to save gwei
if (mode==1) {
// Delete from your Trustee array
for (uint256 i = 0; i < _selfDetermined[_msgSender()].sYouTrust.length; i++) {
if (_selfDetermined[_msgSender()].sYouTrust[i] == _youTrust) {
_selfDetermined[_msgSender()].sYouTrust[i] = _selfDetermined[_msgSender()].sYouTrust[_selfDetermined[_msgSender()].sYouTrust.length - 1];
_selfDetermined[_msgSender()].sYouTrust.pop();
break;
}
}
// Delete from their Trustee array
for (uint256 i = 0; i < _selfDetermined[_youTrust].spTrustYou.length; i++) {
if (_selfDetermined[_youTrust].spTrustYou[i] == _msgSender()) {
_selfDetermined[_youTrust].spTrustYou[i] = _selfDetermined[_youTrust].spTrustYou[_selfDetermined[_youTrust].spTrustYou.length - 1];
_selfDetermined[_youTrust].spTrustYou.pop();
break;
}
}
}
else {
_selfDetermined[_msgSender()].sYouTrust.push(_youTrust); // control who you trust
if (_selfDetermined[_youTrust].spFirstTrustee == address(0)) // you are the first x-persona to trust him, hope you know what you are doing
_selfDetermined[_youTrust].spFirstTrustee = _msgSender(); // it's not reversible
_selfDetermined[_youTrust].spTrustYou.push(_msgSender()); // inform the party you trust him
}
return(_selfDetermined[_msgSender()].sYouTrust.length); // extra useful info
}
// T:OK (f13)
function Finger(address _who) public view returns(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) {
return (_selfDetermined[_who].sPgpPubK,_selfDetermined[_who].sSshPubK,_selfDetermined[_who].sX509PubK,_selfDetermined[_who].sGecos,_selfDetermined[_who].sRole,_selfDetermined[_who].sNickname);
}
// T:OK (f11)
function getTrustChain(address _who) public view
returns(
address _firstTrustee,
address[] memory _youTrust,
uint256 _youTrustCount,
address[] memory _theyTrustU,
uint256 _theyTrustUcount,
uint256[] memory _youAgreementsSigned,
uint256[2] memory _yourTrustPoints
) {
return (
_selfDetermined[_who].spFirstTrustee,
_selfDetermined[_who].sYouTrust,
_selfDetermined[_who].sYouTrust.length,
_selfDetermined[_who].spTrustYou,
_selfDetermined[_who].spTrustYou.length,
_selfDetermined[_who].spYouAgreementsSigned,
_selfDetermined[_who].spTrustPoints
);
}
/**
* In una società di diritto privato gli individui acconsentono volontariamente ai servizi e agli scambi appaltati
* e quindi, devono concordare le clausole di uscita ammende, se applicabili, se il deposito deve essere versato in
* anticipo o le parti concorderanno di pagare alla risoluzione del contratto. Un tribunale di diritto privato o selezionato
* il giudice deve essere scelto come arbitri da tutte le parti di comune accordo. Una controversia deve essere
* avviato dalle parti che hanno firmato il contratto. Viene avviata una controversia, solo l'arbitro deve
* decidere sui motivi. I trasgressori illeciti pagheranno la multa a tutte le altre parti e contrarranno
* la violazione sarà incrementata dall'arbitro. Non viene avviata alcuna controversia, le parti sono d'accordo
* in caso di scioglimento dell'accordo. L'accordo viene sciolto, tutti i firmatari vengono rimborsati delle multe.
* In una società cripto-panarchica, l'arbitrato del tribunale privato deve essere codificato. I Cypherpunk scrivono codice.
*
* T:OK (f9)
**/
// T:OK:(f9)
function setAgreement(uint256 _aid, string memory _hash, string memory _gecos, string memory _url, string memory _signedHash, uint256 _fine, address _arbitrator, uint256 _arbitratorFee, uint256 _deposit, string memory _signComment,uint256 _sign) notPhysicallyRemoved public {
require(_aid>0,"A2: bad id"); // AuthZ: ivalid id for private agreement
require(_selfDetermined[_arbitrator].sRole==1,"A2: court must be Role=1"); // A2: arbitrator or court must set himself Role=1
if(_privLawAgreement[_aid].creator==address(0)) { // doesnt exist, create it
_privLawAgreement[_aid].hash=_hash;
_privLawAgreement[_aid].gecos=_gecos;
_privLawAgreement[_aid].url=_url;
_privLawAgreement[_aid].fine=_fine;
_privLawAgreement[_aid].deposit=_deposit; // 1 = required
_privLawAgreement[_aid].creator=msg.sender;
_privLawAgreement[_aid].arbitrator=_arbitrator;
_privLawAgreement[_aid].arbitratorFee=_arbitratorFee;
_privLawAgreement[_aid].createdOn=block.timestamp;
_privLawAgreementIDs.push(_aid);
} else { // exists, sign it
_setAgreementSign(_aid, _hash, _signedHash, _fine, _arbitrator, _signComment, _sign);
}
}
//T:PEND:(f9):Sign existing agreement. Separated non-public functions to save gas
function _setAgreementSign(uint256 _aid, string memory _hash, string memory _signedHash, uint256 _fine, address _arbitrator, string memory _signComment, uint256 _sign) internal {
require(_fine==_privLawAgreement[_aid].fine,"A2: bad fine"); // AuthZ: fine value mismatch
require(keccak256(abi.encode(_hash))==keccak256(abi.encode(_privLawAgreement[_aid].hash)),"A2: bad hash"); // AuthZ: must reaffirm hash acceptance
require(msg.sender!=_arbitrator,"A2: court can't be party"); // AuthZ: arbitrator can not take part of the agreement
require(_sign==1,"A2: sign it! (aid)"); // AuthZ: agreement ID exists, explicitly consent to sign it
_privLawAgreement[_aid].fine=_fine;
_privLawAgreement[_aid].signedOn[msg.sender]=block.timestamp;
_privLawAgreement[_aid].signedHash[msg.sender]=_signedHash;
_privLawAgreement[_aid].signComment[msg.sender]=_signComment;
if (_privLawAgreement[_aid].finePaid[msg.sender]==0 && _privLawAgreement[_aid].deposit==1) { // must deposit fine in advance in this contract
require(balanceOf(_msgSender()) >= _fine,"E: balance is below fine"); // ERC20: balance below required fine amount, cant sign agreement
transfer(address(this), _fine); // transfer fine deposit to contract T:BUG
//_transfer(_msgSender(), recipient, amount);
_privLawAgreement[_aid].finePaid[msg.sender]=1;
}
(_privLawAgreement[_aid].signature[msg.sender], _privLawAgreement[_aid].signatureNonce[msg.sender]) = xffa.simpleSignSaltedHash("I hereby consent aid");
_selfDetermined[msg.sender].spYouAgreementsSigned.push(_aid);
_privLawAgreement[_aid].signees.push(msg.sender);
_privLawAgreement[_aid].state[msg.sender]=1; // mark active
}
// T:PEND(MERGE):(f9):Allows one to get agreement data and someone's termos to agreement aid
function getAgreementData(uint256 _aid, address _who) public view returns (string memory, string memory, string memory) {
require(_privLawAgreement[_aid].creator!=address(0),"A2: bad aid"); // AuthZ: agreement ID is nonexistant
//require(_privLawAgreement[_aid].signedOn[_who]!=0,"AuthZ: this x-persona did not sign this agreement ID");
bool _validSign = xffa.verifySimpleSignSaltedHash(_privLawAgreement[_aid].signature[_who],_who,"I hereby consent aid",_privLawAgreement[_aid].signatureNonce[_who]);
string memory _vLabel = "false";
if (_validSign==true) _vLabel = "true";
return(
// specifics for signee (_who)
string(abi.encodePacked(
" _signedHash ",_privLawAgreement[_aid].signedHash[_who],
" _signComment ",_privLawAgreement[_aid].signComment[_who],
" _signatureValid ",_vLabel," _signedOn ",xffa.uint2str(_privLawAgreement[_aid].signedOn[_who]),
" _finePaid ",xffa.uint2str(_privLawAgreement[_aid].finePaid[_who]),
" _state ",xffa.uint2str(_privLawAgreement[_aid].state[_who])
)),
// agreement generics (everyone)
string(abi.encodePacked(" _creator ",xffa.anyToStr(_privLawAgreement[_aid].creator),
" _hash ",_privLawAgreement[_aid].hash," _arbitrator ",xffa.anyToStr(_privLawAgreement[_aid].arbitrator),
" _arbitratorFee ", xffa.anyToStr(_privLawAgreement[_aid].arbitratorFee),
" _fine ",xffa.uint2str(_privLawAgreement[_aid].fine)," _gecos ",_privLawAgreement[_aid].gecos,
" _url ",_privLawAgreement[_aid].url
)),
// stack too deep (after merge)
string(abi.encodePacked(" _deposit ",xffa.uint2str(_privLawAgreement[_aid].deposit)
))
);
}
// XXX_Pend: continuar daqui
// T:PEND
function _vai(uint256 _aid) public {
_privLawAgreement[_aid].signees.push(0xD1E1aF95A1Fb9000c0fEe549cD533903DaB8f715);
_privLawAgreement[_aid].signees.push(0x37bB9cC8bf230f5bB11eDC20894d091943f3FdCE);
_privLawAgreement[_aid].signees.push(0x3644B986B3F5Ba3cb8D5627A22465942f8E06d09);
_privLawAgreement[_aid].signees.push(0x000000000000000000000000000000000000dEaD);
_privLawAgreement[_aid].state[0xD1E1aF95A1Fb9000c0fEe549cD533903DaB8f715]=2;
_privLawAgreement[_aid].state[0x37bB9cC8bf230f5bB11eDC20894d091943f3FdCE]=2;
_privLawAgreement[_aid].state[0x3644B986B3F5Ba3cb8D5627A22465942f8E06d09]=_aid;
_privLawAgreement[_aid].state[0x000000000000000000000000000000000000dEaD]=2;
}
//T:OK:(f9):Allows one to get all signees to a given agreement id
function getAgreementSignees(uint256 _aid) public view returns(address[] memory _signees) {
return (_privLawAgreement[_aid].signees);
}
//T:OK:(f9):Allow to test if agreement is settled peacefully (state=2) or not. Returns the first who did not agree if not settled.
function isSettledAgreement(uint256 _aid) public view returns(bool, address _who) {
address _whod;
for (uint256 n=0; n<_privLawAgreement[_aid].signees.length;n++) {
_whod = _privLawAgreement[_aid].signees[n];
if (_privLawAgreement[_aid].state[_whod]!=2)
return (false,_whod);
}
return (true,address(0));
}
//T:OK:(f9):A non public version of the previous function, for testing and not informational
function _isSettledAgreement(uint256 _aid) private view returns(bool) {
address _whod;
for (uint256 n=0; n<_privLawAgreement[_aid].signees.length;n++) {
_whod = _privLawAgreement[_aid].signees[n];
if (_privLawAgreement[_aid].state[_whod]!=2)
return (false);
}
return (true);
}
//T:PEND:Allows withdrawal of deposit if agreement is settled or has been arbitrated
function wdAgreement(uint256 _aid) public {
require(_privLawAgreement[_aid].deposit==1 && _privLawAgreement[_aid].finePaid[_msgSender()]==1,"E: not paid"); // Withdrawal: you never paid deposit for this agreement id
require(_privLawAgreement[_aid].fine>0,"E: nothing to wd"); // Withdrawal: nothing to withdrawal, agreement charged no fine"
require(balanceOf(address(this))>=_privLawAgreement[_aid].fine,"E: contract balance too low"); // Withdrawal: contract balance is too low, arbitrator or crypto-panarchy administration should fund it
require((_privLawAgreement[_aid].state[_msgSender()]==4 || _isSettledAgreement(_aid)),"E: wd not ready"); // Withdrawal: sorry, agreement is neither settled or arbitrated to your favor
/** Precisamos definir o valor. Possibile logica aziendale:
* - se for settlement amigavel, devolve o que pagou, paga fee, mark state 21
* - se for disputa arbitrada mark state 41
* - saca o dobro se for um acordo com apenas duas partes, desconta taxa de arbitragem
* - descobre os perdedores P, descobre o total de perdedores tP divide pelo total de signatararios s, desconta arbitragem e paga a divisao
* - saque = (D*s) - f / (s-tP)
* onde
* tp = total de perdedores da disputa (ie 2)
* s = total de signees (ie 10)
* D = fine depositada per s (ie 60)
* f = tazza de arbittrage (ie 2)
* - ∴ saque = ( (60*10)-3/(10-2) ) ∴ 59962500000 wei
* - arbitragem define outro valor? melhor nao. nel codice, ci fidiamo.
* - pagamento da fee de arbitragem apenas sobre saques individuais, mark state 91
* - fee de arbittrage: max fee absolute hardcoded no contrato (imutavel),
* custom fee absolute, or percentage fee hardcoded no contratto
* therefore we have custom (free market), default in percentage
* and max arbitration fee, which the reason to exist was discussed
* between Tom W Bell & 0xFF4, and is an optional upper limit by the crypto-panarchy.
**/
uint256 tP;
uint256 s=_privLawAgreement[_aid].signees.length;
uint256 D=_privLawAgreement[_aid].fine; //
uint256 fmax=3 * 10**_decimals; // max arbitration fee (in Tokens) (CONFIG:hardcoded)
uint256 fpc=2; // default arbitration fee in percentage (CONFIG:hardcoded)
uint256 f=(D.mul(s)).mul(fpc).div( (10**2)); // default arbitration fee value in tokens
uint256 wdValue;
if (_isSettledAgreement(_aid)) { // its all good, agreement is friendly settled
require(_msgSender()!=_privLawAgreement[_aid].arbitrator,"E:fee not due"); // Withdrawal: friendly settled aid, no arbitration fee is due"
// if (_msgSender()!=_privLawAgreement[_aid].arbitrator) { return false; } // cheaper
wdValue=_privLawAgreement[_aid].fine; // get back what you paid
_privLawAgreement[_aid].state[msg.sender]=21; // mark 21
}
if (_privLawAgreement[_aid].arbitratorFee>0) { f=_privLawAgreement[_aid].arbitratorFee; } // arbitrator has set a custom fee
if (f > fmax) { f=fmax; } // arbitration fee never above fmax for this panarchy.
for (uint256 n=0; n<s; n++) { tP.add(1); } // tP++
if (msg.sender==_privLawAgreement[_aid].arbitrator) { // arbitrator withdrawal
require(_privLawAgreement[_aid].state[_msgSender()]!=91,"E: already paid"); // Withdrawal: arbitrator fee already claimed
wdValue=f;
_privLawAgreement[_aid].state[msg.sender]=91; // mark 91
} else { // signee withdrawal
require(_privLawAgreement[_aid].state[_msgSender()]!=41,"E: already paid"); // "Withdrawal: signee disputed fine already claimed"
wdValue=( (D*s) - f / (s-tP) ); // Der formulae für diesen Panarchy debattiert
_privLawAgreement[_aid].state[msg.sender]=41; // mark 41
}
_approve(address(this), msg.sender, wdValue);
_transfer(address(this), msg.sender, wdValue);
}
// 1=active/signed, 2=want_friendly_terminate, 3=want_dispute, 4=won_dispute, 5=lost_dispute
// 21=friendly_withdrawaled, 41=disputed_wdled, 91=arbitrator_wdled 99=disputed_outside(ostracized)
// T:PEND:(f16):Allows signee to enter dispute, enter friendly agreement and allows court to arbitrate disputes
function setArbitration(uint256 _aid, uint256 _state, address _signee) public returns(bool) {
require((_privLawAgreement[_aid].state[msg.sender]!=1||_privLawAgreement[_aid].arbitrator!=_msgSender()),"A2: not signee/court"); // never signed and is not arbitrator, do nothing
/*if (_privLawAgreement[_aid].state[msg.sender]!=1||_privLawAgreement[_aid].arbitrator!=_msgSender()) {
return false; // never signed and is not arbitrator, do nothing
} else { */
if (_privLawAgreement[_aid].arbitrator==_msgSender() && _state==99) { // worst scenario, arbitrator informs disputed outside
_privLawAgreement[_aid].state[_signee]=99; // set state to 99
_selfDetermined[_signee].spContractsViolated++; // violated contract
_selfDetermined[_signee].spOptOutArbitrations=1; // disputed outside this panarchy rules: ostracized
_selfDetermined[_signee].ostracizedBy.push(_msgSender()); // ostracized by this court
setTrustPoints(_signee, 0); // worsen average
}
if (_privLawAgreement[_aid].arbitrator!=_msgSender() && (_state==2||_state==3||_state==1)) { // signer may set those states
_privLawAgreement[_aid].state[msg.sender]=_state;
} else if (_privLawAgreement[_aid].arbitrator==_msgSender() && (_privLawAgreement[_aid].state[_signee]==3) && (_state==4||_state==5)) { // arbitrator may set those states to signee if he wants dispute arbitration
_privLawAgreement[_aid].state[msg.sender]=_state;
if (_state==4) {
setTrustPoints(_signee, 2); // receives 1 point from contract
} else {
_selfDetermined[_signee].spContractsViolated++; // violated contract
setTrustPoints(_signee, 0); // worsen average
}
}
//}
return true;
}
} //EST FINITO
/*
* Due to contract size restrictions I am continuing the implementation in a second contract called VolNI which continues
* using all the public interfaces from the original Crypto-Panarchy contract. It's a weird design decision which I was
* mostly forced due to Solidity's actual limitations. Luckily all relevant calls were made public to export to Web3js front.
* I am not fully implementing Hayek's idea because I disagree (and Mises does too, you bunch of socialists), therefore
* volNiAddFunds() is still voluntary, one must donate! Belevolence! And members of the trust chain who need money may claim
* a share every 15 days.
*/
contract VolNI is Ownable {
using SafeMath for uint256;
using Address for address;
string public name = "Voluntary Negative Income";
address public panarchyAdmin;
address public panaddr;
mapping (address => uint256) donatesum;
struct volNiSubjProperties {
uint256 lastClaimedDate;
uint256 donateSum;
}
mapping (address => volNiSubjProperties) private _volniSubject;
uint256[3] public benevolSubjStats; // [ epoch, numSubj, totalValue ]
event Deposit(address indexed who, uint amount);
constructor (address _panarchy_addr) {
panaddr = _panarchy_addr;
//panarchy = new XFFAv5();
}
/*receive() external payable { deposit(); }
function deposit() public payable {
p.balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
_volniSubject[msg.sender].donateSum.add(_amount);
}*/
XFFAv5 p = XFFAv5(payable(panaddr));
function mygetAgreementSignees(uint256 _aid) public view returns(address[] memory) {
return(p.getAgreementSignees(_aid));
}
function myPrintParentAddr() public view returns(address) {
return (panaddr);
}
function Finger(address _who) public view returns(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) {
return (p.Finger (_who));
}
function volNiAddFunds(uint256 _amount) public {
require (p.balanceOf(msg.sender)>=_amount,"ERC20: Insufficient balance to donate funds to Voluntary NI");
p.approve(msg.sender, _amount); // _approve(_msgSender(), spender, amount);
p.transfer(address(this), _amount);
_volniSubject[msg.sender].donateSum.add(_amount);
}
function volNiBalance() public view returns(uint256) {
return (p.balanceOf(address(this)));
}
function volNiClaim() public {
require(_volniSubject[msg.sender].lastClaimedDate<=(block.timestamp+1296580),"A2: already claimed within last 15 days"); // 1296580 = 15d 8h
uint256 wdValue=100;
//uint256 wdValue=(p.balanceOf[address(this)].div(benevolSubjStats[1])); // predict monthly NI based on num of beneficiaries from last period
require(p.balanceOf(address(this))>=wdValue/2,"A2: insuficient funds, invite convenant members to donate");
p.approve(address(this), wdValue.div(2)); // divided by two for splitting claims every 15days
p.transfer(msg.sender, wdValue.div(2));
if (benevolSubjStats[0] <= (block.timestamp-2593160)) benevolSubjStats = [ 0, 0, 0 ]; // reset statistics after 1 month
benevolSubjStats = [ block.timestamp, benevolSubjStats[1].add(1), benevolSubjStats[2].add(wdValue.div(2))]; // monthly statistics
_volniSubject[msg.sender].lastClaimedDate=block.timestamp;
}
}
*/
* TODO: so far wdValue is static, I should make it make it a DAO decision. Also test for min balance of claimer and
* track it because low time preference individuals should be detected and are not welcome to get money from this pool.
*/
| Withdrawal: arbitrator fee already claimed
| require(_privLawAgreement[_aid].state[_msgSender()]!=91,"E: already paid"); | 12,876,873 | [
1,
1190,
9446,
287,
30,
10056,
86,
639,
14036,
1818,
7516,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
6647,
2583,
24899,
11365,
48,
2219,
17420,
63,
67,
20736,
8009,
2019,
63,
67,
3576,
12021,
1435,
65,
5,
33,
12416,
10837,
41,
30,
1818,
30591,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "../../v1/Auction.sol";
import "../../v1/FixedPrice.sol";
import "../../v1/OpenOffers.sol";
interface IFarbeMarketplace {
function assignToInstitution(address _institutionAddress, uint256 _tokenId, address _owner) external;
function getIsFarbeMarketplace() external view returns (bool);
}
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArtV3Upgradeable is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, AccessControlUpgradeable {
// counter for tracking token IDs
CountersUpgradeable.Counter internal _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) public tokenIdToDetails;
// not using this here anymore, it has been moved to the farbe marketplace contract
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Initializer for the ERC721 contract
*/
function initialize() public initializer {
__ERC721_init("FarbeArt", "FBA");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721Upgradeable, ERC721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) {
return super.supportsInterface(interfaceId);
}
uint256[1000] private __gap;
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSaleV3Upgradeable is FarbeArtV3Upgradeable {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
using CountersUpgradeable for CountersUpgradeable.Counter;
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
setApprovalForAll(farbeMarketplace, true);
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
if(_galleryAddress != address(0)){
IFarbeMarketplace(farbeMarketplace).assignToInstitution(_galleryAddress, _tokenIdCounter.current(), msg.sender);
}
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Initializer for the FarbeArtSale contract
* name for initializer changed from "initialize" to "farbeInitialze" as it was causing override error with the initializer of NFT contract
*/
function farbeInitialize() public initializer {
FarbeArtV3Upgradeable.initialize();
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
function setFarbeMarketplaceAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
farbeMarketplace = _address;
}
function getTokenCreatorAddress(uint256 _tokenId) public view returns(address) {
return tokenIdToDetails[_tokenId].tokenCreator;
}
function getTokenCreatorCut(uint256 _tokenId) public view returns(uint16) {
return tokenIdToDetails[_tokenId].creatorCut;
}
uint256[1000] private __gap;
// #sbt upgrades-plugin does not support __gaps for now
// so including the new variable here
address public farbeMarketplace;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).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 {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
// 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 CountersUpgradeable {
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 This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./FarbeArt.sol";
import "./SaleBase.sol";
/**
* @title Base auction contract
* @dev This is the base auction contract which implements the auction functionality
*/
contract AuctionBase is SaleBase {
using Address for address payable;
// auction struct to keep track of the auctions
struct Auction {
address seller;
address creator;
address gallery;
address buyer;
uint128 currentPrice;
uint64 duration;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its auction
mapping(uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the auction to the mapping and emit the AuctionCreated event, duration must meet the requirements
* @param _tokenId ID of the token to auction
* @param _auction Reference to the auction struct to add to the mapping
*/
function _addAuction(uint256 _tokenId, Auction memory _auction) internal {
// check minimum and maximum time requirements
require(_auction.duration >= 1 hours && _auction.duration <= 30 days, "time requirement failed");
// update mapping
tokenIdToAuction[_tokenId] = _auction;
// emit event
emit AuctionCreated(
uint256(_tokenId),
uint256(_auction.currentPrice),
uint256(_auction.duration)
);
}
/**
* @dev Remove the auction from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove auction of
*/
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/**
* @dev Internal function to check the current price of the auction
* @param auction Reference to the auction to check price of
* @return uint128 The current price of the auction
*/
function _currentPrice(Auction storage auction) internal view returns (uint128) {
return (auction.currentPrice);
}
/**
* @dev Internal function to return the bid to the previous bidder if there was one
* @param _destination Address of the previous bidder
* @param _amount Amount to return to the previous bidder
*/
function _returnBid(address payable _destination, uint256 _amount) private {
// zero address means there was no previous bidder
if (_destination != address(0)) {
_destination.sendValue(_amount);
}
}
/**
* @dev Internal function to check if an auction started. By default startedAt is at 0
* @param _auction Reference to the auction struct to check
* @return bool Weather the auction has started
*/
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0 && _auction.startedAt <= block.timestamp);
}
/**
* @dev Internal function to implement the bid functionality
* @param _tokenId ID of the token to bid upon
* @param _bidAmount Amount to bid
*/
function _bid(uint _tokenId, uint _bidAmount) internal {
// get reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// check if the item is on auction
require(_isOnAuction(auction), "Item is not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed <= auction.duration, "Auction time has ended");
// check if bid is higher than the previous one
uint256 price = auction.currentPrice;
require(_bidAmount > price, "Bid is too low");
// return the previous bidder's bid amount
_returnBid(payable(auction.buyer), auction.currentPrice);
// update the current bid amount and the bidder address
auction.currentPrice = uint128(_bidAmount);
auction.buyer = msg.sender;
// if the bid is made in the last 15 minutes, increase the duration of the
// auction so that the timer resets to 15 minutes
uint256 timeRemaining = auction.duration - secondsPassed;
if (timeRemaining <= 15 minutes) {
uint256 timeToAdd = 15 minutes - timeRemaining;
auction.duration += uint64(timeToAdd);
}
}
/**
* @dev Internal function to finish the auction after the auction time has ended
* @param _tokenId ID of the token to finish auction of
*/
function _finishAuction(uint256 _tokenId) internal {
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// if there was no successful bid, return token to the seller
if (referenceAuction.buyer == address(0)) {
_transfer(referenceAuction.seller, _tokenId);
emit AuctionSuccessful(
_tokenId,
0,
referenceAuction.seller
);
}
// if there was a successful bid, pay the seller and transfer the token to the buyer
else {
_payout(
payable(referenceAuction.seller),
payable(referenceAuction.creator),
payable(referenceAuction.gallery),
referenceAuction.creatorCut,
referenceAuction.platformCut,
referenceAuction.galleryCut,
referenceAuction.currentPrice,
_tokenId
);
_transfer(referenceAuction.buyer, _tokenId);
emit AuctionSuccessful(
_tokenId,
referenceAuction.currentPrice,
referenceAuction.buyer
);
}
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function _forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
internal
{
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// check if its been more than 7 days since auction ended
require(secondsPassed - auction.duration >= 7 days);
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// transfer ether to the beneficiary
payable(_paymentBeneficiary).sendValue(referenceAuction.currentPrice);
// transfer nft to the nft beneficiary
_transfer(_nftBeneficiary, _tokenId);
}
}
/**
* @title Auction sale contract that provides external functions
* @dev Implements the external and public functions of the auction implementation
*/
contract AuctionSale is AuctionBase {
// sanity check for the nft contract
bool public isFarbeSaleAuction = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create auction. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create auction for
* @param _startingPrice Starting price of the auction in wei
* @param _duration Duration of the auction in seconds
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this auction, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the auction
Auction memory auction = Auction(
_seller,
_creator,
_gallery,
address(0),
uint128(_startingPrice),
uint64(_duration),
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addAuction(_tokenId, auction);
}
/**
* @dev External payable bid function. Sellers can not bid on their own artworks
* @param _tokenId ID of the token to bid on
*/
function bid(uint256 _tokenId) external payable {
// do not allow sellers and galleries to bid on their own artwork
require(tokenIdToAuction[_tokenId].seller != msg.sender && tokenIdToAuction[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_bid(_tokenId, msg.value);
}
/**
* @dev External function to finish the auction. Currently can be called by anyone TODO restrict access?
* @param _tokenId ID of the token to finish auction of
*/
function finishAuction(uint256 _tokenId) external {
_finishAuction(_tokenId);
}
/**
* @dev External view function to get the details of an auction
* @param _tokenId ID of the token to get the auction information of
* @return seller Address of the seller
* @return buyer Address of the buyer
* @return currentPrice Current Price of the auction in wei
* @return duration Duration of the auction in seconds
* @return startedAt Unix timestamp for when the auction started
*/
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
address buyer,
uint256 currentPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.buyer,
auction.currentPrice,
auction.duration,
auction.startedAt
);
}
/**
* @dev External view function to get the current price of an auction
* @param _tokenId ID of the token to get the current price of
* @return uint128 Current price of the auction in wei
*/
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint128)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp,
uint256 duration
) {
Auction memory auction = tokenIdToAuction[_tokenId];
return (auction.startedAt, block.timestamp, auction.duration);
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_forceFinishAuction(_tokenId, _nftBeneficiary, _paymentBeneficiary);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./SaleBase.sol";
/**
* @title Base fixed price contract
* @dev This is the base fixed price contract which implements the internal functionality
*/
contract FixedPriceBase is SaleBase {
using Address for address payable;
// fixed price sale struct to keep track of the sales
struct FixedPrice {
address seller;
address creator;
address gallery;
uint128 fixedPrice;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => FixedPrice) tokenIdToSale;
event FixedSaleCreated(uint256 tokenId, uint256 fixedPrice);
event FixedSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the sale to the mapping and emit the FixedSaleCreated event
* @param _tokenId ID of the token to sell
* @param _fixedSale Reference to the sale struct to add to the mapping
*/
function _addSale(uint256 _tokenId, FixedPrice memory _fixedSale) internal {
// update mapping
tokenIdToSale[_tokenId] = _fixedSale;
// emit event
emit FixedSaleCreated(
uint256(_tokenId),
uint256(_fixedSale.fixedPrice)
);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal function to check if a sale started. By default startedAt is at 0
* @param _fixedSale Reference to the sale struct to check
* @return bool Weather the sale has started
*/
function _isOnSale(FixedPrice storage _fixedSale) internal view returns (bool) {
return (_fixedSale.startedAt > 0 && _fixedSale.startedAt <= block.timestamp);
}
/**
* @dev Internal function to buy a token on sale
* @param _tokenId Id of the token to buy
* @param _amount The amount in wei
*/
function _buy(uint256 _tokenId, uint256 _amount) internal {
// get reference to the fixed price sale struct
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(fixedSale), "Item is not on sale");
// check if sent amount is equal or greater than the set price
require(_amount >= fixedSale.fixedPrice, "Amount sent is not enough to buy the token");
// using struct to avoid stack too deep error
FixedPrice memory referenceFixedSale = fixedSale;
// delete the sale
_removeSale(_tokenId);
// pay the seller, and distribute cuts
_payout(
payable(referenceFixedSale.seller),
payable(referenceFixedSale.creator),
payable(referenceFixedSale.gallery),
referenceFixedSale.creatorCut,
referenceFixedSale.platformCut,
referenceFixedSale.galleryCut,
_amount,
_tokenId
);
// transfer the token to the buyer
_transfer(msg.sender, _tokenId);
emit FixedSaleSuccessful(_tokenId, referenceFixedSale.fixedPrice, msg.sender);
}
/**
* @dev Function to finish the sale. Can be called manually if no one bought the NFT. If
* a gallery put the artwork on sale, only it can call this function. The super admin can
* also call the function, this is implemented as a safety mechanism for the seller in case
* the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// only the gallery can finish the sale if it was the one to put it on auction
if(fixedSale.gallery != address(0)) {
require(fixedSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(fixedSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(fixedSale));
address seller = fixedSale.seller;
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Fixed Price sale contract that provides external functions
* @dev Implements the external and public functions of the Fixed price implementation
*/
contract FixedPriceSale is FixedPriceBase {
// sanity check for the nft contract
bool public isFarbeFixedSale = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create fixed sale. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create sale for
* @param _fixedPrice Starting price of the sale in wei
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this sale, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the sale
FixedPrice memory fixedSale = FixedPrice(
_seller,
_creator,
_gallery,
_fixedPrice,
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addSale(_tokenId, fixedSale);
}
/**
* @dev External payable function to buy the artwork
* @param _tokenId Id of the token to buy
*/
function buy(uint256 _tokenId) external payable {
// do not allow sellers and galleries to buy their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_buy(_tokenId, msg.value);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
/**
* @dev External view function to get the details of a sale
* @param _tokenId ID of the token to get the sale information of
* @return seller Address of the seller
* @return fixedPrice Fixed Price of the sale in wei
* @return startedAt Unix timestamp for when the sale started
*/
function getFixedSale(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 fixedPrice,
uint256 startedAt
) {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
require(_isOnSale(fixedSale), "Item is not on sale");
return (
fixedSale.seller,
fixedSale.fixedPrice,
fixedSale.startedAt
);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp
) {
FixedPrice memory fixedSale = tokenIdToSale[_tokenId];
return (fixedSale.startedAt, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/PullPayment.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./SaleBase.sol";
import "../EnumerableMap.sol";
/**
* @title Base open offers contract
* @dev This is the base contract which implements the open offers functionality
*/
contract OpenOffersBase is PullPayment, ReentrancyGuard, SaleBase {
using Address for address payable;
// Add the library methods
using EnumerableMap for EnumerableMap.AddressToUintMap;
struct OpenOffers {
address seller;
address creator;
address gallery;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
EnumerableMap.AddressToUintMap offers;
}
// this struct is only used for referencing in memory. The OpenOffers struct can not
// be used because it is only valid in storage since it contains a nested mapping
struct OffersReference {
address seller;
address creator;
address gallery;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => OpenOffers) tokenIdToSale;
event OpenOffersSaleCreated(uint256 tokenId);
event OpenOffersSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Internal function to check if the sale started, by default startedAt will be 0
*
*/
function _isOnSale(OpenOffers storage _openSale) internal view returns (bool) {
return (_openSale.startedAt > 0 && _openSale.startedAt <= block.timestamp);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal that updates the mapping when a new offer is made for a token on sale
* @param _tokenId Id of the token to make offer on
* @param _bidAmount The offer in wei
*/
function _makeOffer(uint _tokenId, uint _bidAmount) internal {
// get reference to the open offer struct
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(openSale));
uint256 returnAmount;
bool offerExists;
// get reference to the amount to return
(offerExists, returnAmount) = openSale.offers.tryGet(msg.sender);
// update the mapping with the new offer
openSale.offers.set(msg.sender, _bidAmount);
// if there was a previous offer from this address, return the previous offer amount
if(offerExists){
payable(msg.sender).sendValue(returnAmount);
}
}
/**
* @dev Internal function to accept the offer of an address. Once an offer is accepted, all existing offers
* for the token are moved into the PullPayment contract and the mapping is deleted. Only gallery can accept
* offers if the sale involves a gallery
* @param _tokenId Id of the token to accept offer of
* @param _buyer The address of the buyer to accept offer from
*/
function _acceptOffer(uint256 _tokenId, address _buyer) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery can accept the offer if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender);
} else {
require(openSale.seller == msg.sender);
}
// check if token was on sale
require(_isOnSale(openSale));
// check if the offer from the buyer exists
require(openSale.offers.contains(_buyer));
// get reference to the offer
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
address returnAddress;
uint256 returnAmount;
// put the returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// using struct to avoid stack too deep error
OffersReference memory openSaleReference = OffersReference(
openSale.seller,
openSale.creator,
openSale.gallery,
openSale.creatorCut,
openSale.platformCut,
openSale.galleryCut
);
// delete the sale
_removeSale(_tokenId);
// pay the seller and distribute the cuts
_payout(
payable(openSaleReference.seller),
payable(openSaleReference.creator),
payable(openSaleReference.gallery),
openSaleReference.creatorCut,
openSaleReference.platformCut,
openSaleReference.galleryCut,
_payoutAmount,
_tokenId
);
// transfer the token to the buyer
_transfer(_buyer, _tokenId);
}
/**
* @dev Internal function to cancel an offer. This is used for both rejecting and revoking offers
* @param _tokenId Id of the token to cancel offer of
* @param _buyer The address to cancel bid of
*/
function _cancelOffer(uint256 _tokenId, address _buyer) internal {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if token was on sale
require(_isOnSale(openSale));
// get reference to the offer, will fail if mapping doesn't exist
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
// return the ether
payable(_buyer).sendValue(_payoutAmount);
}
/**
* @dev Function to finish the sale. Can be called manually if there was no suitable offer
* for the NFT. If a gallery put the artwork on sale, only it can call this function.
* The super admin can also call the function, this is implemented as a safety mechanism for
* the seller in case the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery or admin can finish the sale if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(openSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(openSale));
address seller = openSale.seller;
address returnAddress;
uint256 returnAmount;
// put all pending returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Open Offers sale contract that provides external functions
* @dev Implements the external and public functions of the open offers implementation
*/
contract OpenOffersSale is OpenOffersBase {
bool public isFarbeOpenOffersSale = true;
/**
* External function to create an Open Offers sale. Can only be called by the Farbe NFT contract
* @param _tokenId Id of the token to create sale for
* @param _startingTime Starting time of the sale
* @param _creator Address of the original creator of the artwork
* @param _seller Address of the owner of the artwork
* @param _gallery Address of the gallery of the artwork, 0 address if gallery is not involved
* @param _creatorCut Cut of the creator in %age * 10
* @param _galleryCut Cut of the gallery in %age * 10
* @param _platformCut Cut of the platform on primary sales in %age * 10
*/
function createSale(
uint256 _tokenId,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
OpenOffers storage openOffers = tokenIdToSale[_tokenId];
openOffers.seller = _seller;
openOffers.creator = _creator;
openOffers.gallery = _gallery;
openOffers.startedAt = _startingTime;
openOffers.creatorCut = _creatorCut;
openOffers.platformCut = _platformCut;
openOffers.galleryCut = _galleryCut;
}
/**
* @dev External function that allows others to make offers for an artwork
* @param _tokenId Id of the token to make offer for
*/
function makeOffer(uint256 _tokenId) external payable {
// do not allow sellers and galleries to make offers on their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_makeOffer(_tokenId, msg.value);
}
/**
* @dev External function to allow a gallery or a seller to accept an offer
* @param _tokenId Id of the token to accept offer of
* @param _buyer Address of the buyer to accept offer of
*/
function acceptOffer(uint256 _tokenId, address _buyer) external {
_acceptOffer(_tokenId, _buyer);
}
/**
* @dev External function to reject a particular offer and return the ether
* @param _tokenId Id of the token to reject offer of
* @param _buyer Address of the buyer to reject offer of
*/
function rejectOffer(uint256 _tokenId, address _buyer) external {
// only owner or gallery can reject an offer
require(tokenIdToSale[_tokenId].seller == msg.sender || tokenIdToSale[_tokenId].gallery == msg.sender);
_cancelOffer(_tokenId, _buyer);
}
/**
* @dev External function to allow buyers to revoke their offers
* @param _tokenId Id of the token to revoke offer of
*/
function revokeOffer(uint256 _tokenId) external {
_cancelOffer(_tokenId, msg.sender);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./OpenOffers.sol";
import "./Auction.sol";
import "./FixedPrice.sol";
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArt is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControl {
// counter for tracking token IDs
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) tokenIdToDetails;
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Constructor for the ERC721 contract
*/
constructor() ERC721("FarbeArt", "FBA") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
approve(_galleryAddress, _tokenIdCounter.current());
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721, ERC721URIStorage) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721, ERC721Enumerable, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSale is FarbeArt {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
/**
* @dev Set the primary platform cut on deployment
* @param _platformCut Cut that the platform will take on primary sales
*/
constructor(uint16 _platformCut) {
platformCutOnPrimarySales = _platformCut;
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setAuctionContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
AuctionSale auction = AuctionSale(_address);
require(auction.isFarbeSaleAuction());
auctionSale = auction;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setFixedSaleContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
FixedPriceSale fixedSale = FixedPriceSale(_address);
require(fixedSale.isFarbeFixedSale());
fixedPriceSale = fixedSale;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setOpenOffersContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
OpenOffersSale openOffers = OpenOffersSale(_address);
require(openOffers.isFarbeOpenOffersSale());
openOffersSale = openOffers;
}
/**
* @dev Set the percentage cut that the platform will take on all primary sales
* @param _platformCut The cut that the platform will take on primary sales as %age * 10 for values < 1%
*/
function setPlatformCut(uint16 _platformCut) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformCutOnPrimarySales = _platformCut;
}
/**
* @dev Track artwork as sold before by updating the mapping. Can only be called by the sales contracts
* @param _tokenId The id of the token which was sold
*/
function setSecondarySale(uint256 _tokenId) external {
require(msg.sender != address(0));
require(msg.sender == address(auctionSale) || msg.sender == address(fixedPriceSale)
|| msg.sender == address(openOffersSale), "Caller is not a farbe sale contract");
tokenIdToDetails[_tokenId].isSecondarySale = true;
}
/**
* @dev Checks from the mapping if the token has been sold before
* @param _tokenId ID of the token to check
* @return bool Weather this is a secondary sale (token has been sold before)
*/
function getSecondarySale(uint256 _tokenId) public view returns (bool) {
return tokenIdToDetails[_tokenId].isSecondarySale;
}
/**
* @dev Creates the sale auction for the token by calling the external auction contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingPrice Starting price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _duration The duration in seconds for the auction
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleAuction(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(_seller, address(auctionSale), _tokenId);
// call the external contract function to create the auction
auctionSale.createSale(
_tokenId,
_startingPrice,
_startingTime,
_duration,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the fixed price sale for the token by calling the external fixed sale contract. Can only be called by owner.
* Individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _fixedPrice Fixed price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleFixedPrice(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(fixedPriceSale), _tokenId);
// call the external contract function to create the auction
fixedPriceSale.createSale(
_tokenId,
_fixedPrice,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the open offer sale for the token by calling the external open offers contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleOpenOffer(
uint256 _tokenId,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(openOffersSale), _tokenId);
// call the external contract function to create the auction
openOffersSale.createSale(
_tokenId,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./FarbeArt.sol";
contract SaleBase is IERC721Receiver, AccessControl {
using Address for address payable;
// reference to the NFT contract
FarbeArtSale public NFTContract;
// address of the platform wallet to which the platform cut will be sent
address internal platformWalletAddress;
modifier onlyFarbeContract() {
// check the caller is the FarbeNFT contract
require(msg.sender == address(NFTContract), "Caller is not the Farbe contract");
_;
}
/**
* @dev Implementation of ERC721Receiver
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes memory _data
) public override virtual returns (bytes4) {
// This will fail if the received token is not a FarbeArt token
// _owns calls NFTContract
require(_owns(address(this), _tokenId), "owner is not the sender");
return this.onERC721Received.selector;
}
/**
* @dev Internal function to check if address owns a token
* @param _claimant The address to check
* @param _tokenId ID of the token to check for ownership
* @return bool Weather the _claimant owns the _tokenId
*/
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (NFTContract.ownerOf(_tokenId) == _claimant);
}
/**
* @dev Internal function to transfer the NFT from this contract to another address
* @param _receiver The address to send the NFT to
* @param _tokenId ID of the token to transfer
*/
function _transfer(address _receiver, uint256 _tokenId) internal {
NFTContract.safeTransferFrom(address(this), _receiver, _tokenId);
}
/**
* @dev Internal function that calculates the cuts of all parties and distributes the payment among them
* @param _seller Address of the seller
* @param _creator Address of the original creator
* @param _gallery Address of the gallery, 0 address if gallery is not involved
* @param _creatorCut The cut of the original creator
* @param _platformCut The cut that goes to the Farbe platform
* @param _galleryCut The cut that goes to the gallery
* @param _amount The total amount to be split
* @param _tokenId The ID of the token that was sold
*/
function _payout(
address payable _seller,
address payable _creator,
address payable _gallery,
uint16 _creatorCut,
uint16 _platformCut,
uint16 _galleryCut,
uint256 _amount,
uint256 _tokenId
) internal {
// if this is a secondary sale
if (NFTContract.getSecondarySale(_tokenId)) {
// initialize amount to send to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale, wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)){
galleryAmount = (_galleryCut * _amount) / 1000;
}
// platform gets 2.5% on secondary sales (hard-coded)
uint256 platformAmount = (25 * _amount) / 1000;
// calculate amount to send to creator
uint256 creatorAmount = (_creatorCut * _amount) / 1000;
// calculate amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + creatorAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
payable(platformWalletAddress).sendValue(platformAmount);
_creator.sendValue(creatorAmount);
_seller.sendValue(sellerAmount);
}
// if this is a primary sale
else {
require(_seller == _creator, "Seller is not the creator");
// dividing by 1000 because percentages are multiplied by 10 for values < 1%
uint256 platformAmount = (_platformCut * _amount) / 1000;
// initialize amount to be sent to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)) {
galleryAmount = (_galleryCut * _amount) / 1000;
}
// calculate the amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
_seller.sendValue(sellerAmount);
payable(platformWalletAddress).sendValue(platformAmount);
// set secondary sale to true
NFTContract.setSecondarySale(_tokenId);
}
}
/**
* @dev External function to allow admin to change the address of the platform wallet
* @param _address Address of the new wallet
*/
function setPlatformWalletAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformWalletAddress = _address;
}
}
// 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}. 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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @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 { }
}
// 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";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../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;
/**
* @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 "../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;
/**
* @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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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 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 "../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 "../utils/escrow/Escrow.sol";
/**
* @dev Simple implementation of a
* https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
* strategy, where the paying contract doesn't interact directly with the
* receiver account, which must withdraw its payments itself.
*
* Pull-payments are often considered the best practice when it comes to sending
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* 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].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
*/
abstract contract PullPayment {
Escrow immutable private _escrow;
constructor () {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated payments, forwarding all gas to the recipient.
*
* Note that _any_ account can call this function, not just the `payee`.
* This means that contracts unaware of the `PullPayment` protocol can still
* receive funds this way, by having a separate account call
* {withdrawPayments}.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee Whose payments will be withdrawn.
*/
function withdrawPayments(address payable payee) public virtual {
_escrow.withdraw(payee);
}
/**
* @dev Returns the payments owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* Funds sent in this way are stored in an intermediate {Escrow} contract, so
* there is no danger of them being spent before withdrawal.
*
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{ value: amount }(dest);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @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.AddressToUintMap;
*
* // Declare a set state variable
* EnumerableMap.AddressToUintMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `address -> uint256` (`AddressToUintMap`) are
* supported.
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// 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 Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @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) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @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) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @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._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.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) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @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) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @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) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @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) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// AddressToUintMap
struct AddressToUintMap {
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(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(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(AddressToUintMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap 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(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), 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(AddressToUintMap storage map, address key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(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(
AddressToUintMap storage map,
address key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key))), errorMessage));
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../access/Ownable.sol";
import "../Address.sol";
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
*
* Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the `Escrow` rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its owner, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Ownable {
using Address for address payable;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public payable virtual onlyOwner {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee] + amount;
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee, forwarding all gas to the
* recipient.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public virtual onlyOwner {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.sendValue(payment);
emit Withdrawn(payee, payment);
}
}
// 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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// 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] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
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));
}
} | #sbt upgrades-plugin does not support __gaps for now so including the new variable here | address public farbeMarketplace;
| 60,715 | [
1,
18366,
88,
28844,
17,
4094,
1552,
486,
2865,
1001,
75,
6679,
364,
2037,
1427,
6508,
326,
394,
2190,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1758,
1071,
10247,
2196,
3882,
24577,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//SPDX-License-Identifier: Unlicensed
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
//ANTIS INU (THE SHIBA KILLER)
//https://antisinu.com
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%%##*********##%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#*+=============-------=+*#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@%#*++++*##%@@@@@@@@@@@@@@@@%#**+===+#%@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@#*++*#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#*+++*#@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@#*=+*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#*++*%@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@*==+#@@@@@@@@%%@@@@@@@@@@@@@@@@@@@@@@@@@%%@@@@@@@#*++#@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@*==+%@@@@@@@@%####%%@@@@@@@@@@@@@@@@@@@%%%###%@@@@@@@%*==*@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@*--+%@@@@@@@@@@##*+**%%%@@@@@@@@@@@@@@@%%%#*+*##@@@@@@@@@%+==*@@@@@@@@@@@@@@
@@@@@@@@@@@@%=-=#@@@@@@@@@@@@#+==+=+#%%@@@@@@@@@@@@@@%#+=++=+*%@@@@@@@@@@%=-=#@@@@@@@@@@@@
@@@@@@@@@@@*--+@@@@@@@@@@@@@#+===+==*%%@@@@@@@@@@@@@%%*==+====*@@@@@@@@@@@@*--+@@@@@@@@@@@
@@@@@@@@@@=:-#@@@@@@@@@@@@@@#++===+=+%%@@@@@@@@@@@@@%%+=++==++*@@@@@@@@@@@@@%--=@@@@@@@@@@
@@@@@@@@@-:-%@@@@@@@@@@@@@@#*++++=+==#%%@@@@@@@@@@@%%#==+==++++#@@@@@@@@@@@@@%=:-@@@@@@@@@
@@@@@@@@=:-%@@@@@@@@@@@@@@@+=++=++=++%%%@@@@@@@@@@@%%%+++++=++=+%@@@@@@@@@@@@@@-:-@@@@@@@@
@@@@@@@+::%@@@@@@@@@@@@@@@#++=+==+++*%%%%@@@@@@@@@%%%%*+++==+=++*@@@@@@@@@@@@@@%-:=@@@@@@@
@@@@@@#::*@@@@@@@@@@@@@@@@*=++++===+########%%%########+===++++=+@@@@@@@@@@@@@@@*::#@@@@@@
@@@@@@-:-@@@@@@@@@@@@@@@@@+++=+++=+******++*****++******+=+++=+++@@@@@@@@@@@@@@@@-::@@@@@@
@@@@@#.:*@@@@@@@@@@@@@@@@@*+=++++****++====+***+====++****++++++*@@@@@@@@@@@@@@@@#:.*@@@@@
@@@@@=.:@@@@@@@@@@@@@@@@@@#*++=+*#*++=======+*+========+*#*+==+*#@@@@@@@@@@@@@@@@@:.-@@@@@
@@@@@:.-@@@@@@@@@@@@@@@@@@%***+*#*+==========*==========+*#*+***#@@@@@@@@@@@@@@@@@=..@@@@@
@@@@@..+@@@@@@@@@@@@@@@@@@%######+=====+====+*+====+=====+######%@@@@@@@@@@@@@@@@@+..%@@@@
@@@@%..+@@@@@@@@@@@@@@@@@@%#%%%#+===+*%%%===***+==#%%#+===+#%%%##@@@@@@@@@@@@@@@@@*..%@@@@
@@@@@..+@@@@@@@@@@@@@@@@@@@%###*===#***@%*=*****=+%%#**#+==+####@@@@@@@@@@@@@@@@@@+..%@@@@
@@@@@:.-@@@@@@@@@@@@@@@@@@@@%##====*######*******###%##*====##%@@@@@@@@@@@@@@@@@@@=..@@@@@
@@@@@=.:@@@@@@@@@@@@@@@@@@@@@#*========+****###****++=======*#@@@@@@@@@@@@@@@@@@@@:.-@@@@@
@@@@@#.:*@@@@@@@@@@@@@@@@@@@%#**++======***#####***======++**#%@@@@@@@@@@@@@@@@@@#:.*@@@@@
@@@@@@-:-@@@@@@@@@@@@@@@@@@%#****+=====+*#########*+=====+****#%@@@@@@@@@@@@@@@@@-::@@@@@@
@@@@@@#::*@@@@@@@@@@@@@@@@%****+******+#############*+*****+**#*#@@@@@@@@@@@@@@@*::*@@@@@@
@@@@@@@+::%@@@@@@@@@@@@@@@%@@#++******###**+===++*###******++#@@%@@@@@@@@@@@@@@%-:=@@@@@@@
@@@@@@@@-:-%@@@@@@@@@@@@@@@@@#+*******####%%%#%%%####*******+#@@@@@@@@@@@@@@@@@-:-@@@@@@@@
@@@@@@@@@-:-%@@@@@@@@@@@@@@@@#+*#*+***####%@@@@@%#####**+*#**#@@@@@@@@@@@@@@@@=:-@@@@@@@@@
@@@@@@@@@@=:-#@@@@@@@@@@@@@@@%#@@*+**#######%%%#######**+*%@%#@@@@@@@@@@@@@@%--=@@@@@@@@@@
@@@@@@@@@@@+--*@@@@@@@@@@@@@@@@@@****######%%%%%######****@@@@@@@@@@@@@@@@@*--+@@@@@@@@@@@
@@@@@@@@@@@@#--=%@@@@@@@@@@@@@@@@%@#***#############***#@%@@@@@@@@@@@@@@@%+-=#@@@@@@@@@@@@
@@@@@@@@@@@@@@*--+%@@@@@@@@@@@@@@@@@#***++*+++++**+***#@@@@@@@@@@@@@@@@%*==*@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@*==+%@@@@@@@@@@@@@@@@#%*****++++**+*%#@@@@@@@@@@@@@@@%*==*@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@*==+#@@@@@@@@@@@@@@@@@%@%#+++*%@#@@@@@@@@@@@@@@@@%*++*@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@#+=+*#@@@@@@@@@@@@@@@@@@%+#@@@@@@@@@@@@@@@@@#*++*#@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@#*++*#%@@@@@@@@@@@@@@@#@@@@@@@@@@@@@@%*+++*#@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@%#*+++**#%%@@@@@@@@@@@@@@@@%##*+===+*%@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#**+==============------=+*#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%##****++++**##%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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 {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/3_Ballot.sol
pragma solidity ^0.8.10;
contract AntisInuToken is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
uint256 public swapTokensAtAmount = 2 * 10**7 * (10**9);
uint256 public maxWalletLimit = 15 * 10**8 * 10**9; // 3% of the supply
uint256 public maxTxAmount = 25 * 10**7 * 10**9; // 0.5% of the supply
uint8 public marketingFee = 10;
uint16 internal totalFees = marketingFee;
address public bridge;
address payable public _marketingWallet = payable(address(0x456)); // MARKETING WALLET
mapping (address => bool) public _isBlacklisted;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
constructor(address _bridge) ERC20("ANTIS INU", "ANTIS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
bridge = _bridge;
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(_bridge, true);
excludeFromFees(address(this), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(_bridge, 30 * 10**9 * (10**9)); // 30,000,000,000 Tokens
}
receive() external payable {}
function decimals() public pure override returns(uint8) {
return 9;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "COOL: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
uniswapV2Pair = _uniswapV2Pair;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
require(_isExcludedFromFees[account] != excluded, "COOL: Account is already excluded");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function setMarketingWallet(address payable wallet) external onlyOwner{
_marketingWallet = wallet;
}
function addToBlackList (address [] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++ i) {
_isBlacklisted [addresses [i]] = true;}
}
function setSwapAtAmount(uint256 value) external onlyOwner {
swapTokensAtAmount = value;
}
function setMaxWalletAmount(uint256 value) external onlyOwner {
maxWalletLimit = value;
}
function setMaxTxAmount(uint256 value) external onlyOwner {
maxTxAmount = value;
}
function setmarketingFee(uint8 value) external onlyOwner{
marketingFee = value;
totalFees = marketingFee;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "COOL: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require (! _isBlacklisted [from] &&! _isBlacklisted [to], "This address is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if( canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
contractTokenBalance = swapTokensAtAmount;
swapAndSendToFee(contractTokenBalance);
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
require(amount <= maxTxAmount,"Transfer amount exceeds limit");
if(!automatedMarketMakerPairs[to]){
require(amount + balanceOf(to) <= maxWalletLimit,"Wallet limit reached");
}
uint256 fees = amount.mul(totalFees).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
}
function claimStuckTokens(address _token) external onlyOwner {
if (_token == address(0x0)) {
payable(owner()).transfer(address(this).balance);
return;
}
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.transfer(owner(), balance);
}
function swapAndSendToFee(uint256 tokens) private {
uint256 initialBalance = address(this).balance;
swapTokensForBNB(tokens);
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 forMarketing = newBalance;
_marketingWallet.transfer(forMarketing);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
} | if any account belongs to _isExcludedFromFee account then remove the fee | function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require (! _isBlacklisted [from] &&! _isBlacklisted [to], "This address is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if( canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
contractTokenBalance = swapTokensAtAmount;
swapAndSendToFee(contractTokenBalance);
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
require(amount <= maxTxAmount,"Transfer amount exceeds limit");
if(!automatedMarketMakerPairs[to]){
require(amount + balanceOf(to) <= maxWalletLimit,"Wallet limit reached");
}
uint256 fees = amount.mul(totalFees).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
}
| 1,110,229 | [
1,
430,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
540,
2583,
16051,
389,
291,
13155,
18647,
306,
2080,
65,
597,
5,
389,
291,
13155,
18647,
306,
869,
6487,
315,
2503,
1758,
353,
25350,
8863,
203,
203,
203,
3639,
309,
12,
8949,
422,
374,
13,
288,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
374,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
202,
202,
11890,
5034,
6835,
1345,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
1426,
848,
12521,
273,
6835,
1345,
13937,
1545,
7720,
5157,
861,
6275,
31,
203,
203,
3639,
309,
12,
848,
12521,
597,
203,
5411,
401,
22270,
1382,
597,
203,
5411,
401,
5854,
362,
690,
3882,
278,
12373,
10409,
63,
2080,
65,
597,
203,
5411,
628,
480,
3410,
1435,
597,
203,
5411,
358,
480,
3410,
1435,
203,
3639,
262,
288,
203,
5411,
7720,
1382,
273,
638,
31,
203,
203,
5411,
6835,
1345,
13937,
273,
7720,
5157,
861,
6275,
31,
203,
203,
5411,
7720,
1876,
3826,
774,
14667,
12,
16351,
1345,
13937,
1769,
203,
203,
5411,
7720,
1382,
273,
629,
31,
203,
3639,
289,
203,
203,
203,
3639,
1426,
4862,
14667,
273,
401,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./LandNFT.sol";
contract LockedNFT is Ownable, ReentrancyGuard, IERC721Receiver {
// Address of the nft contract
address NFTAddress;
// Standard timelock (5 years)
uint256 public totalLockup = 1825 days;
// Lockup
uint256 public monthlyLockup = 30 days;
// retirement pct
uint256 public retirementPercentage = 1;
// Mapping from token Id to the timestamp when it was staked
// in this contract
mapping(uint256 => uint256) private lockStartTime;
// Mapping from address to the total staked/bought
mapping(address => uint256) private totalStakedByAddress;
mapping(address => uint256) private totalBoughtByAddress;
// Mapping from buyer/landowner to list of buyed/staked token ids
mapping(address => mapping(uint256 => uint256)) private boughtLands;
mapping(address => mapping(uint256 => uint256)) private stakedLands;
// Mapping from tokenId to buyer/landowner index
mapping(uint256 => uint256) private boughtLandsIndex;
mapping(uint256 => uint256) private stakedLandsIndex;
// Arrays with all staked/buyed ids, used for enumeration
uint256[] public _allStakedTokens;
uint256[] public _allBoughtTokens;
// Mappings from token id to all tokens posiiton
mapping(uint256 => uint256) private allStakedIndex;
mapping(uint256 => uint256) private allBoughtIndex;
// mapping from token id to current celo balance locked
mapping(uint256 => uint256) private stakedBalance;
// mapping from token id to harvests made
mapping(uint256 => uint256) private harvests;
constructor(address _NFTAddress) {
NFTAddress = _NFTAddress;
}
receive() external payable {}
fallback() external payable {}
/**
@dev Deposit a new land nft to the marketplace
*/
function depositNFT(uint256 tokenId) public nonReentrant {
ILandNFT ilandInterface = ILandNFT(NFTAddress);
IERC721 erc721 = IERC721(NFTAddress);
// Get the the land balance
uint256 landBalance = erc721.balanceOf(msg.sender);
require(landBalance > 0, "You're currently owning zero lands");
require(
erc721.ownerOf(tokenId) == msg.sender,
"You're not the owner of this land!"
);
// Deposit the nft to the marketplace and mark it as available
ilandInterface.safeTransferToMarketplace(msg.sender, tokenId);
increaseStakedCount(msg.sender, tokenId);
}
/**
@dev Withdraw a staked land nft from the marketplace
*/
function withdrawNFT(uint256 tokenId) public nonReentrant {
ILandNFT ilandInterface = ILandNFT(NFTAddress);
IERC721 erc721 = IERC721(NFTAddress);
require(
totalStakedByAddress[msg.sender] > 0,
"You have not any land in marketplace!"
);
require(
ilandInterface.landOwnerOf(tokenId) == msg.sender,
"You're not the land owner of this NFT Land!"
);
require(elapsedTime(tokenId) >= totalLockup, "NFT is still locked!");
// Transfer back the nft to the land owner
erc721.safeTransferFrom(address(this), msg.sender, tokenId);
// update the land state to mavailable
ilandInterface.updateLandState(tokenId, State.Active);
// reset the lock start time of token
delete lockStartTime[tokenId];
// update the staked count
decreaseStakedCount(msg.sender, tokenId);
}
/**
@dev Allows a buyer to buy a new nft and lock the contract
*/
function buyNFT(uint256 tokenId) external payable nonReentrant {
ILandNFT ilandInterface = ILandNFT(NFTAddress);
require(
ilandInterface.stateOf(tokenId) == State.MAvailable,
"This land NFT is not available!"
);
require(
msg.value >= ilandInterface.initialPriceOf(tokenId),
"The amount of CELO sent is not enough!"
);
require(
msg.sender != ilandInterface.landOwnerOf(tokenId),
"You can't buy your own land!"
);
// Receive the amount of CELO sent
(bool sent, ) = address(this).call{value: msg.value}("");
require(sent, "Failed to send CELO");
// Update land status
ilandInterface.updateLandState(tokenId, State.MLocked);
// Set the initial lock to current timestamp
lockStartTime[tokenId] = block.timestamp;
/* Update the total land bought by the buyer
and add the new nft to its collection */
increaseBoughtCount(msg.sender, tokenId);
// Update the buyer
ilandInterface.updateBuyer(tokenId, msg.sender);
// set the staked balance
stakedBalance[tokenId] = msg.value;
// set the initial lockup info of this land
harvests[tokenId] = 0;
}
function withdrawAllCeloStaked(uint256 tokenId) external {
ILandNFT ilandInterface = ILandNFT(NFTAddress);
IERC721 erc721 = IERC721(NFTAddress);
require(
erc721.ownerOf(tokenId) == address(this),
"This land is not staked here!"
);
require(
ilandInterface.buyerOf(tokenId) == msg.sender,
"You havent bought this land!"
);
require(elapsedTime(tokenId) >= totalLockup, "NFT is still locked!");
// set the state to market unavailable
ilandInterface.updateLandState(tokenId, State.MUnavailable);
// get the celo locked
uint256 _stakedBalance = stakedBalance[tokenId];
// decrease the current bought lands
decreaseBoughtCount(msg.sender, tokenId);
// Transfer the amount of celo Locked
payable(msg.sender).transfer(_stakedBalance);
// reset buyer to 0 address
ilandInterface.updateBuyer(tokenId, address(0));
// reset the staked balance of this land
delete stakedBalance[tokenId];
// reset the harvests info of this land
delete harvests[tokenId];
}
function withdrawMonthlyCelo(uint256 tokenId) external {
ILandNFT ilandInterface = ILandNFT(NFTAddress);
require(
ilandInterface.buyerOf(tokenId) == msg.sender,
"You havent bought this land!"
);
// get the harvests to make
uint256 _harvestsToMake = harvestsToMake(tokenId);
require(
_harvestsToMake >= 1,
"You should wait until next harvest period!"
);
// Calculate the amount to retire
uint256 harvestAmount = getHarvestAmount(tokenId);
// Update the number of harvests made
harvests[tokenId]++;
// Send the tokens to buyer
payable(msg.sender).transfer(harvestAmount);
// Update the staked balance of the land
stakedBalance[tokenId] -= harvestAmount;
}
function getHarvestAmount(uint256 tokenId) public view returns (uint256) {
ILandNFT ilandInterface = ILandNFT(NFTAddress);
uint256 currentPriceOf = ilandInterface.currentPriceOf(tokenId);
uint256 _harvestsToMake = harvestsToMake(tokenId);
// Amount to retrieve will be the 1% times the harvests available
// of the land's staked balance
uint256 harvestAmount = (currentPriceOf *
_harvestsToMake *
retirementPercentage) / 100;
return harvestAmount;
}
function currentHarvestsOf(uint256 tokenId) public view returns (uint256) {
return harvests[tokenId];
}
function harvestsToMake(uint256 tokenId) public view returns (uint256) {
// Get elapsed months from initial start time
uint256 _elapsedMonths = elapsedMonths(tokenId);
if (_elapsedMonths == 0){
return 0;
}
// Get amount of harvests done
uint256 currentHarvests = currentHarvestsOf(tokenId);
// Calculate harvests that can be made this month
return 60 / (_elapsedMonths - currentHarvests);
}
function getNextHarvestPeriod(uint256 tokenId)
public
view
returns (uint256)
{
// get the harvests to make
uint256 _harvestsToMake = harvestsToMake(tokenId);
return lockStartTime[tokenId] + (monthlyLockup * _harvestsToMake);
}
/**
@dev Returns the amount of CELO in this contract
*/
function getBalance() public view returns (uint256) {
return address(this).balance;
}
function totalStaked() public view returns (uint256) {
return _allStakedTokens.length;
}
function totalStakedBy(address landOwner) public view returns (uint256) {
return totalStakedByAddress[landOwner];
}
function totalBought() public view returns (uint256) {
return _allBoughtTokens.length;
}
function totalBoughtBy(address buyer) public view returns (uint256) {
return totalBoughtByAddress[buyer];
}
function timelocked() public view returns (uint256) {
return totalLockup;
}
/**
@dev Disable the timelock for debugging purposes
*/
function disableTimelock() public onlyOwner {
totalLockup = 0;
}
/**
@dev Enables the default timelock of 5 years
*/
function enableTimelock() public onlyOwner {
totalLockup = 1825 days;
}
/**
@dev Gets the elapsed time since the nft got staked and
the current block timestamp
*/
function elapsedTime(uint256 tokenId) public view returns (uint256) {
uint256 _elapsedTime = block.timestamp - lockStartTime[tokenId];
return _elapsedTime;
}
function elapsedMonths(uint256 tokenId) public view returns (uint256) {
return elapsedTime(tokenId) / monthlyLockup;
}
function lockStart(uint256 tokenId) public view returns (uint256) {
return lockStartTime[tokenId];
}
function increaseStakedCount(address landOwner, uint256 tokenId) private {
// Sum a new nft to the total staked by this address
totalStakedByAddress[landOwner] = totalStakedByAddress[landOwner] + 1;
// Get the total staked by address
uint256 _totalStakedByThisAddress = totalStakedByAddress[landOwner];
// Update the reference of the nfts staked by this address
stakedLands[landOwner][_totalStakedByThisAddress] = tokenId;
// Assign the index of a token Id to the owners index
stakedLandsIndex[tokenId] = _totalStakedByThisAddress;
// Update the all bought info
allStakedIndex[tokenId] = _allStakedTokens.length;
_allStakedTokens.push(tokenId);
}
function decreaseStakedCount(address landOwner, uint256 tokenId) private {
// Get the total staked by address and the token index
uint256 lastLandIndex = totalStakedByAddress[landOwner] - 1;
uint256 landIndex = stakedLandsIndex[tokenId];
// When the Land to delete is the last Land
// the swap operation is unnecesary
if (landIndex != lastLandIndex) {
uint256 lastLandId = stakedLands[landOwner][lastLandIndex];
stakedLands[landOwner][landIndex] = lastLandId; // Move the last Land to the slot of the to-delete Land
stakedLandsIndex[lastLandId] = landIndex; // Update the moved Land's index
}
// This also deletes the contents at the last position of the array
delete stakedLandsIndex[tokenId];
delete stakedLands[landOwner][lastLandIndex];
// Decrease a nft of the total Staked by this address
totalStakedByAddress[landOwner]--;
// remove from global info
removeLandFromAllStakedEnumeration(tokenId);
}
function increaseBoughtCount(address buyer, uint256 tokenId) private {
// Sum a new nft to the total Bought by this address
totalBoughtByAddress[buyer] = totalBoughtByAddress[buyer] + 1;
// Get the total Bought by address
uint256 _totalBoughtByThisAddress = totalBoughtByAddress[buyer];
// Update the reference of the nfts Bought by this address
boughtLands[buyer][_totalBoughtByThisAddress] = tokenId;
// Assign the index of a token Id to the owners index
boughtLandsIndex[tokenId] = _totalBoughtByThisAddress;
// Update the all bought info
allBoughtIndex[tokenId] = _allBoughtTokens.length;
_allBoughtTokens.push(tokenId);
}
function decreaseBoughtCount(address buyer, uint256 tokenId) private {
// Get the total Bought by address and the token index
uint256 lastLandIndex = totalBoughtByAddress[buyer] - 1;
uint256 landIndex = boughtLandsIndex[tokenId];
// When the Land to delete is the last Land
// the swap operation is unnecesary
if (landIndex != lastLandIndex) {
uint256 lastLandId = boughtLands[buyer][lastLandIndex];
boughtLands[buyer][landIndex] = lastLandId; // Move the last Land to the slot of the to-delete Land
boughtLandsIndex[lastLandId] = landIndex; // Update the moved Land's index
}
// This also deletes the contents at the last position of the array
delete boughtLandsIndex[tokenId];
delete boughtLands[buyer][lastLandIndex];
// Decrease a nft of the total Bought by this address
totalBoughtByAddress[buyer]--;
// Remove from the all tokens info
removeLandFromAllBoughtEnumeration(tokenId);
}
function removeLandFromAllStakedEnumeration(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 = _allStakedTokens.length - 1;
uint256 tokenIndex = allStakedIndex[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 = allStakedIndex[lastTokenIndex];
_allStakedTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
allStakedIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete allStakedIndex[tokenId];
_allStakedTokens.pop();
}
function removeLandFromAllBoughtEnumeration(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 = _allBoughtTokens.length - 1;
uint256 tokenIndex = allBoughtIndex[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 = allBoughtIndex[lastTokenIndex];
_allBoughtTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
allBoughtIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete allBoughtIndex[tokenId];
_allBoughtTokens.pop();
}
/**
@dev Returns a buyed land of an address given an index
*/
function landOfBuyerByIndex(address buyer, uint256 index)
public
view
returns (uint256)
{
require(
index < totalBoughtByAddress[buyer],
"Buyer index out of bounds"
);
return boughtLands[buyer][index];
}
/**
@dev returns the index position of a NFT in a buyers collection
*/
function indexOfBoughtLand(uint256 tokenId) public view returns (uint256) {
require(_allStakedTokens.length > 0, "There is nothing staked");
require(_allBoughtTokens.length > 0, "There is no land bought yet");
return boughtLandsIndex[tokenId];
}
function allStakedTokens() public view returns (uint256[] memory) {
return _allStakedTokens;
}
function allBoughtTokens() public view returns (uint256[] memory) {
return _allBoughtTokens;
}
function getMontlyLockup() public view returns (uint256) {
return monthlyLockup;
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
return this.onERC721Received.selector;
}
}
| remove from global info | removeLandFromAllStakedEnumeration(tokenId);
| 7,310,507 | [
1,
4479,
628,
2552,
1123,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1206,
29398,
1265,
1595,
510,
9477,
21847,
12,
2316,
548,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
import "../lib/ERC1271.sol";
import "../lib/OwnerManagable.sol";
import "../lib/SignatureUtil.sol";
/// @title OfficialGuardian
/// @author Freeman Zhong - <[email protected]>
contract OfficialGuardian is OwnerManagable, ERC1271
{
using SignatureUtil for bytes32;
/// @dev init owner for proxy contract:
function initOwner(address _owner)
external
{
require(owner == address(0), "INITIALIZED_ALREADY");
owner = _owner;
}
function isValidSignature(
bytes32 _signHash,
bytes memory _signature
)
public
view
override
returns (bytes4)
{
return isManager(_signHash.recoverECDSASigner(_signature))?
ERC1271_MAGICVALUE:
bytes4(0);
}
function transact(
address target,
uint value,
bytes calldata data
)
external
onlyManager
returns (
bool success,
bytes memory returnData
)
{
// solium-disable-next-line security/no-call-value
(success, returnData) = target.call{value: value}(data);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValue);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
import "./AddressSet.sol";
import "./Claimable.sol";
contract OwnerManagable is Claimable, AddressSet
{
bytes32 internal constant MANAGER = keccak256("__MANAGED__");
event ManagerAdded (address indexed manager);
event ManagerRemoved(address indexed manager);
modifier onlyManager
{
require(isManager(msg.sender), "NOT_MANAGER");
_;
}
modifier onlyOwnerOrManager
{
require(msg.sender == owner || isManager(msg.sender), "NOT_OWNER_OR_MANAGER");
_;
}
constructor() Claimable() {}
/// @dev Gets the managers.
/// @return The list of managers.
function managers()
public
view
returns (address[] memory)
{
return addressesInSet(MANAGER);
}
/// @dev Gets the number of managers.
/// @return The numer of managers.
function numManagers()
public
view
returns (uint)
{
return numAddressesInSet(MANAGER);
}
/// @dev Checks if an address is a manger.
/// @param addr The address to check.
/// @return True if the address is a manager, False otherwise.
function isManager(address addr)
public
view
returns (bool)
{
return isAddressInSet(MANAGER, addr);
}
/// @dev Adds a new manager.
/// @param manager The new address to add.
function addManager(address manager)
public
onlyOwner
{
addManagerInternal(manager);
}
/// @dev Removes a manager.
/// @param manager The manager to remove.
function removeManager(address manager)
public
onlyOwner
{
removeAddressFromSet(MANAGER, manager);
emit ManagerRemoved(manager);
}
function addManagerInternal(address manager)
internal
{
addAddressToSet(MANAGER, manager, true);
emit ManagerAdded(manager);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "../thirdparty/BytesUtil.sol";
import "./AddressUtil.sol";
import "./ERC1271.sol";
import "./MathUint.sol";
/// @title SignatureUtil
/// @author Daniel Wang - <[email protected]>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @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_MAINTAILED");
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;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
import "./Ownable.sol";
/// @title Claimable
/// @author Brecht Devos - <[email protected]>
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable
{
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title Ownable
/// @author Brecht Devos - <[email protected]>
/// @dev The Ownable contract has an owner address, and provides basic
/// authorization control functions, this simplifies the implementation of
/// "user permissions".
contract Ownable
{
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @dev The Ownable constructor sets the original `owner` of the contract
/// to the sender.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// SPDX-License-Identifier: UNLICENSED
// Taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
pragma solidity ^0.7.0;
library BytesUtil {
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title Utility Functions for addresses
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
internal
view
returns (bool)
{
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success,) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
| solium-disable-next-line security/no-call-value | function transact(
address target,
uint value,
bytes calldata data
)
external
onlyManager
returns (
bool success,
bytes memory returnData
)
{
}
| 11,825,870 | [
1,
18281,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
1991,
17,
1132,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
906,
621,
12,
203,
3639,
1758,
225,
1018,
16,
203,
3639,
2254,
377,
460,
16,
203,
3639,
1731,
565,
745,
892,
501,
203,
3639,
262,
203,
3639,
3903,
203,
3639,
1338,
1318,
203,
3639,
1135,
261,
203,
5411,
1426,
2216,
16,
203,
5411,
1731,
3778,
327,
751,
203,
3639,
262,
203,
565,
288,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
//Swap Deployer functions - descriptions can be found in Deployer.sol
interface Deployer_Interface {
function newContract(address _party, address user_contract, uint _start_date) external payable returns (address);
}
//Slightly modified SafeMath library - includes a min function
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;
}
function min(uint a, uint b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
//Swap factory functions - descriptions can be found in Factory.sol
interface Factory_Interface {
function createToken(uint _supply, address _party, uint _start_date) external returns (address,address, uint);
function payToken(address _party, address _token_add) external;
function deployContract(uint _start_date) external payable returns (address);
function getBase() external view returns(address);
function getVariables() external view returns (address, uint, uint, address,uint);
function isWhitelisted(address _member) external view returns (bool);
}
/**
*The DRCTLibrary contains the reference code used in the DRCT_Token (an ERC20 compliant token
*representing the payout of the swap contract specified in the Factory contract).
*/
library DRCTLibrary{
using SafeMath for uint256;
/*Structs*/
/**
*@dev Keeps track of balance amounts in the balances array
*/
struct Balance {
address owner;
uint amount;
}
struct TokenStorage{
//This is the factory contract that the token is standardized at
address factory_contract;
//Total supply of outstanding tokens in the contract
uint total_supply;
//Mapping from: swap address -> user balance struct (index for a particular user's balance can be found in swap_balances_index)
mapping(address => Balance[]) swap_balances;
//Mapping from: swap address -> user -> swap_balances index
mapping(address => mapping(address => uint)) swap_balances_index;
//Mapping from: user -> dynamic array of swap addresses (index for a particular swap can be found in user_swaps_index)
mapping(address => address[]) user_swaps;
//Mapping from: user -> swap address -> user_swaps index
mapping(address => mapping(address => uint)) user_swaps_index;
//Mapping from: user -> total balance accross all entered swaps
mapping(address => uint) user_total_balances;
//Mapping from: owner -> spender -> amount allowed
mapping(address => mapping(address => uint)) allowed;
}
/*Events*/
/**
*@dev events for transfer and approvals
*/
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
event CreateToken(address _from, uint _value);
/*Functions*/
/**
*@dev Constructor - sets values for token name and token supply, as well as the
*factory_contract, the swap.
*@param _factory
*/
function startToken(TokenStorage storage self,address _factory) public {
self.factory_contract = _factory;
}
/**
*@dev ensures the member is whitelisted
*@param _member is the member address that is chekced agaist the whitelist
*/
function isWhitelisted(TokenStorage storage self,address _member) internal view returns(bool){
Factory_Interface _factory = Factory_Interface(self.factory_contract);
return _factory.isWhitelisted(_member);
}
/**
*@dev gets the factory address
*/
function getFactoryAddress(TokenStorage storage self) external view returns(address){
return self.factory_contract;
}
/**
*@dev Token Creator - This function is called by the factory contract and creates new tokens
*for the user
*@param _supply amount of DRCT tokens created by the factory contract for this swap
*@param _owner address
*@param _swap address
*/
function createToken(TokenStorage storage self,uint _supply, address _owner, address _swap) public{
require(msg.sender == self.factory_contract);
//Update total supply of DRCT Tokens
self.total_supply = self.total_supply.add(_supply);
//Update the total balance of the owner
self.user_total_balances[_owner] = self.user_total_balances[_owner].add(_supply);
//If the user has not entered any swaps already, push a zeroed address to their user_swaps mapping to prevent default value conflicts in user_swaps_index
if (self.user_swaps[_owner].length == 0)
self.user_swaps[_owner].push(address(0x0));
//Add a new swap index for the owner
self.user_swaps_index[_owner][_swap] = self.user_swaps[_owner].length;
//Push a new swap address to the owner's swaps
self.user_swaps[_owner].push(_swap);
//Push a zeroed Balance struct to the swap balances mapping to prevent default value conflicts in swap_balances_index
self.swap_balances[_swap].push(Balance({
owner: 0,
amount: 0
}));
//Add a new owner balance index for the swap
self.swap_balances_index[_swap][_owner] = 1;
//Push the owner's balance to the swap
self.swap_balances[_swap].push(Balance({
owner: _owner,
amount: _supply
}));
emit CreateToken(_owner,_supply);
}
/**
*@dev Called by the factory contract, and pays out to a _party
*@param _party being paid
*@param _swap address
*/
function pay(TokenStorage storage self,address _party, address _swap) public{
require(msg.sender == self.factory_contract);
uint party_balance_index = self.swap_balances_index[_swap][_party];
require(party_balance_index > 0);
uint party_swap_balance = self.swap_balances[_swap][party_balance_index].amount;
//reduces the users totals balance by the amount in that swap
self.user_total_balances[_party] = self.user_total_balances[_party].sub(party_swap_balance);
//reduces the total supply by the amount of that users in that swap
self.total_supply = self.total_supply.sub(party_swap_balance);
//sets the partys balance to zero for that specific swaps party balances
self.swap_balances[_swap][party_balance_index].amount = 0;
}
/**
*@dev Returns the users total balance (sum of tokens in all swaps the user has tokens in)
*@param _owner user address
*@return user total balance
*/
function balanceOf(TokenStorage storage self,address _owner) public constant returns (uint balance) {
return self.user_total_balances[_owner];
}
/**
*@dev Getter for the total_supply of tokens in the contract
*@return total supply
*/
function totalSupply(TokenStorage storage self) public constant returns (uint _total_supply) {
return self.total_supply;
}
/**
*@dev Removes the address from the swap balances for a swap, and moves the last address in the
*swap into their place
*@param _remove address of prevous owner
*@param _swap address used to get last addrss of the swap to replace the removed address
*/
function removeFromSwapBalances(TokenStorage storage self,address _remove, address _swap) internal {
uint last_address_index = self.swap_balances[_swap].length.sub(1);
address last_address = self.swap_balances[_swap][last_address_index].owner;
//If the address we want to remove is the final address in the swap
if (last_address != _remove) {
uint remove_index = self.swap_balances_index[_swap][_remove];
//Update the swap's balance index of the last address to that of the removed address index
self.swap_balances_index[_swap][last_address] = remove_index;
//Set the swap's Balance struct at the removed index to the Balance struct of the last address
self.swap_balances[_swap][remove_index] = self.swap_balances[_swap][last_address_index];
}
//Remove the swap_balances index for this address
delete self.swap_balances_index[_swap][_remove];
//Finally, decrement the swap balances length
self.swap_balances[_swap].length = self.swap_balances[_swap].length.sub(1);
}
/**
*@dev This is the main function to update the mappings when a transfer happens
*@param _from address to send funds from
*@param _to address to send funds to
*@param _amount amount of token to send
*/
function transferHelper(TokenStorage storage self,address _from, address _to, uint _amount) internal {
//Get memory copies of the swap arrays for the sender and reciever
address[] memory from_swaps = self.user_swaps[_from];
//Iterate over sender's swaps in reverse order until enough tokens have been transferred
for (uint i = from_swaps.length.sub(1); i > 0; i--) {
//Get the index of the sender's balance for the current swap
uint from_swap_user_index = self.swap_balances_index[from_swaps[i]][_from];
Balance memory from_user_bal = self.swap_balances[from_swaps[i]][from_swap_user_index];
//If the current swap will be entirely depleted - we remove all references to it for the sender
if (_amount >= from_user_bal.amount) {
_amount -= from_user_bal.amount;
//If this swap is to be removed, we know it is the (current) last swap in the user's user_swaps list, so we can simply decrement the length to remove it
self.user_swaps[_from].length = self.user_swaps[_from].length.sub(1);
//Remove the user swap index for this swap
delete self.user_swaps_index[_from][from_swaps[i]];
//If the _to address already holds tokens from this swap
if (self.user_swaps_index[_to][from_swaps[i]] != 0) {
//Get the index of the _to balance in this swap
uint to_balance_index = self.swap_balances_index[from_swaps[i]][_to];
assert(to_balance_index != 0);
//Add the _from tokens to _to
self.swap_balances[from_swaps[i]][to_balance_index].amount = self.swap_balances[from_swaps[i]][to_balance_index].amount.add(from_user_bal.amount);
//Remove the _from address from this swap's balance array
removeFromSwapBalances(self,_from, from_swaps[i]);
} else {
//Prepare to add a new swap by assigning the swap an index for _to
if (self.user_swaps[_to].length == 0){
self.user_swaps[_to].push(address(0x0));
}
self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length;
//Add the new swap to _to
self.user_swaps[_to].push(from_swaps[i]);
//Give the reciever the sender's balance for this swap
self.swap_balances[from_swaps[i]][from_swap_user_index].owner = _to;
//Give the reciever the sender's swap balance index for this swap
self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances_index[from_swaps[i]][_from];
//Remove the swap balance index from the sending party
delete self.swap_balances_index[from_swaps[i]][_from];
}
//If there is no more remaining to be removed, we break out of the loop
if (_amount == 0)
break;
} else {
//The amount in this swap is more than the amount we still need to transfer
uint to_swap_balance_index = self.swap_balances_index[from_swaps[i]][_to];
//If the _to address already holds tokens from this swap
if (self.user_swaps_index[_to][from_swaps[i]] != 0) {
//Because both addresses are in this swap, and neither will be removed, we simply update both swap balances
self.swap_balances[from_swaps[i]][to_swap_balance_index].amount = self.swap_balances[from_swaps[i]][to_swap_balance_index].amount.add(_amount);
} else {
//Prepare to add a new swap by assigning the swap an index for _to
if (self.user_swaps[_to].length == 0){
self.user_swaps[_to].push(address(0x0));
}
self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length;
//And push the new swap
self.user_swaps[_to].push(from_swaps[i]);
//_to is not in this swap, so we give this swap a new balance index for _to
self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances[from_swaps[i]].length;
//And push a new balance for _to
self.swap_balances[from_swaps[i]].push(Balance({
owner: _to,
amount: _amount
}));
}
//Finally, update the _from user's swap balance
self.swap_balances[from_swaps[i]][from_swap_user_index].amount = self.swap_balances[from_swaps[i]][from_swap_user_index].amount.sub(_amount);
//Because we have transferred the last of the amount to the reciever, we break;
break;
}
}
}
/**
*@dev ERC20 compliant transfer function
*@param _to Address to send funds to
*@param _amount Amount of token to send
*@return true for successful
*/
function transfer(TokenStorage storage self, address _to, uint _amount) public returns (bool) {
require(isWhitelisted(self,_to));
uint balance_owner = self.user_total_balances[msg.sender];
if (
_to == msg.sender ||
_to == address(0) ||
_amount == 0 ||
balance_owner < _amount
) return false;
transferHelper(self,msg.sender, _to, _amount);
self.user_total_balances[msg.sender] = self.user_total_balances[msg.sender].sub(_amount);
self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
*@dev ERC20 compliant transferFrom function
*@param _from address to send funds from (must be allowed, see approve function)
*@param _to address to send funds to
*@param _amount amount of token to send
*@return true for successful
*/
function transferFrom(TokenStorage storage self, address _from, address _to, uint _amount) public returns (bool) {
require(isWhitelisted(self,_to));
uint balance_owner = self.user_total_balances[_from];
uint sender_allowed = self.allowed[_from][msg.sender];
if (
_to == _from ||
_to == address(0) ||
_amount == 0 ||
balance_owner < _amount ||
sender_allowed < _amount
) return false;
transferHelper(self,_from, _to, _amount);
self.user_total_balances[_from] = self.user_total_balances[_from].sub(_amount);
self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);
self.allowed[_from][msg.sender] = self.allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
*@dev ERC20 compliant approve function
*@param _spender party that msg.sender approves for transferring funds
*@param _amount amount of token to approve for sending
*@return true for successful
*/
function approve(TokenStorage storage self, address _spender, uint _amount) public returns (bool) {
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
*@dev Counts addresses involved in the swap based on the length of balances array for _swap
*@param _swap address
*@return the length of the balances array for the swap
*/
function addressCount(TokenStorage storage self, address _swap) public constant returns (uint) {
return self.swap_balances[_swap].length;
}
/**
*@dev Gets the owner address and amount by specifying the swap address and index
*@param _ind specified index in the swap
*@param _swap specified swap address
*@return the owner address associated with a particular index in a particular swap
*@return the amount to transfer associated with a particular index in a particular swap
*/
function getBalanceAndHolderByIndex(TokenStorage storage self, uint _ind, address _swap) public constant returns (uint, address) {
return (self.swap_balances[_swap][_ind].amount, self.swap_balances[_swap][_ind].owner);
}
/**
*@dev Gets the index by specifying the swap and owner addresses
*@param _owner specifed address
*@param _swap specified swap address
*@return the index associated with the _owner address in a particular swap
*/
function getIndexByAddress(TokenStorage storage self, address _owner, address _swap) public constant returns (uint) {
return self.swap_balances_index[_swap][_owner];
}
/**
*@dev Look up how much the spender or contract is allowed to spend?
*@param _owner
*@param _spender party approved for transfering funds
*@return the allowed amount _spender can spend of _owner's balance
*/
function allowance(TokenStorage storage self, address _owner, address _spender) public constant returns (uint) {
return self.allowed[_owner][_spender];
}
}
/**
*The DRCT_Token is an ERC20 compliant token representing the payout of the swap contract
*specified in the Factory contract.
*Each Factory contract is specified one DRCT Token and the token address can contain many
*different swap contracts that are standardized at the Factory level.
*The logic for the functions in this contract is housed in the DRCTLibary.sol.
*/
contract DRCT_Token {
using DRCTLibrary for DRCTLibrary.TokenStorage;
/*Variables*/
DRCTLibrary.TokenStorage public drct;
/*Functions*/
/**
*@dev Constructor - sets values for token name and token supply, as well as the
*factory_contract, the swap.
*@param _factory
*/
constructor() public {
drct.startToken(msg.sender);
}
/**
*@dev Token Creator - This function is called by the factory contract and creates new tokens
*for the user
*@param _supply amount of DRCT tokens created by the factory contract for this swap
*@param _owner address
*@param _swap address
*/
function createToken(uint _supply, address _owner, address _swap) public{
drct.createToken(_supply,_owner,_swap);
}
/**
*@dev gets the factory address
*/
function getFactoryAddress() external view returns(address){
return drct.getFactoryAddress();
}
/**
*@dev Called by the factory contract, and pays out to a _party
*@param _party being paid
*@param _swap address
*/
function pay(address _party, address _swap) public{
drct.pay(_party,_swap);
}
/**
*@dev Returns the users total balance (sum of tokens in all swaps the user has tokens in)
*@param _owner user address
*@return user total balance
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return drct.balanceOf(_owner);
}
/**
*@dev Getter for the total_supply of tokens in the contract
*@return total supply
*/
function totalSupply() public constant returns (uint _total_supply) {
return drct.totalSupply();
}
/**
*ERC20 compliant transfer function
*@param _to Address to send funds to
*@param _amount Amount of token to send
*@return true for successful
*/
function transfer(address _to, uint _amount) public returns (bool) {
return drct.transfer(_to,_amount);
}
/**
*@dev ERC20 compliant transferFrom function
*@param _from address to send funds from (must be allowed, see approve function)
*@param _to address to send funds to
*@param _amount amount of token to send
*@return true for successful transfer
*/
function transferFrom(address _from, address _to, uint _amount) public returns (bool) {
return drct.transferFrom(_from,_to,_amount);
}
/**
*@dev ERC20 compliant approve function
*@param _spender party that msg.sender approves for transferring funds
*@param _amount amount of token to approve for sending
*@return true for successful
*/
function approve(address _spender, uint _amount) public returns (bool) {
return drct.approve(_spender,_amount);
}
/**
*@dev Counts addresses involved in the swap based on the length of balances array for _swap
*@param _swap address
*@return the length of the balances array for the swap
*/
function addressCount(address _swap) public constant returns (uint) {
return drct.addressCount(_swap);
}
/**
*@dev Gets the owner address and amount by specifying the swap address and index
*@param _ind specified index in the swap
*@param _swap specified swap address
*@return the amount to transfer associated with a particular index in a particular swap
*@return the owner address associated with a particular index in a particular swap
*/
function getBalanceAndHolderByIndex(uint _ind, address _swap) public constant returns (uint, address) {
return drct.getBalanceAndHolderByIndex(_ind,_swap);
}
/**
*@dev Gets the index by specifying the swap and owner addresses
*@param _owner specifed address
*@param _swap specified swap address
*@return the index associated with the _owner address in a particular swap
*/
function getIndexByAddress(address _owner, address _swap) public constant returns (uint) {
return drct.getIndexByAddress(_owner,_swap);
}
/**
*@dev Look up how much the spender or contract is allowed to spend?
*@param _owner address
*@param _spender party approved for transfering funds
*@return the allowed amount _spender can spend of _owner's balance
*/
function allowance(address _owner, address _spender) public constant returns (uint) {
return drct.allowance(_owner,_spender);
}
}
//ERC20 function interface with create token and withdraw
interface Wrapped_Ether_Interface {
function totalSupply() external constant returns (uint);
function balanceOf(address _owner) external constant returns (uint);
function transfer(address _to, uint _amount) external returns (bool);
function transferFrom(address _from, address _to, uint _amount) external returns (bool);
function approve(address _spender, uint _amount) external returns (bool);
function allowance(address _owner, address _spender) external constant returns (uint);
function withdraw(uint _value) external;
function createToken() external;
}
interface Membership_Interface {
function getMembershipType(address _member) external constant returns(uint);
}
/**
*The Factory contract sets the standardized variables and also deploys new contracts based on
*these variables for the user.
*/
contract Factory {
using SafeMath for uint256;
/*Variables*/
//Addresses of the Factory owner and oracle. For oracle information,
//check www.github.com/DecentralizedDerivatives/Oracles
address public owner;
address public oracle_address;
//Address of the user contract
address public user_contract;
//Address of the deployer contract
address internal deployer_address;
Deployer_Interface internal deployer;
address public token;
//A fee for creating a swap in wei. Plan is for this to be zero, however can be raised to prevent spam
uint public fee;
//swap fee
uint public swapFee;
//Duration of swap contract in days
uint public duration;
//Multiplier of reference rate. 2x refers to a 50% move generating a 100% move in the contract payout values
uint public multiplier;
//Token_ratio refers to the number of DRCT Tokens a party will get based on the number of base tokens. As an example, 1e15 indicates that a party will get 1000 DRCT Tokens based upon 1 ether of wrapped wei.
uint public token_ratio;
//Array of deployed contracts
address[] public contracts;
uint[] public startDates;
address public memberContract;
mapping(uint => bool) whitelistedTypes;
mapping(address => uint) public created_contracts;
mapping(address => uint) public token_dates;
mapping(uint => address) public long_tokens;
mapping(uint => address) public short_tokens;
mapping(address => uint) public token_type; //1=short 2=long
/*Events*/
//Emitted when a Swap is created
event ContractCreation(address _sender, address _created);
/*Modifiers*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*Functions*/
/**
*@dev Constructor - Sets owner
*/
constructor() public {
owner = msg.sender;
}
/**
*@dev constructor function for cloned factory
*/
function init(address _owner) public{
require(owner == address(0));
owner = _owner;
}
/**
*@dev Sets the Membership contract address
*@param _memberContract The new membership address
*/
function setMemberContract(address _memberContract) public onlyOwner() {
memberContract = _memberContract;
}
/**
*@dev Sets the member types/permissions for those whitelisted
*@param _memberTypes is the list of member types
*/
function setWhitelistedMemberTypes(uint[] _memberTypes) public onlyOwner(){
whitelistedTypes[0] = false;
for(uint i = 0; i<_memberTypes.length;i++){
whitelistedTypes[_memberTypes[i]] = true;
}
}
/**
*@dev Checks the membership type/permissions for whitelisted members
*@param _member address to get membership type from
*/
function isWhitelisted(address _member) public view returns (bool){
Membership_Interface Member = Membership_Interface(memberContract);
return whitelistedTypes[Member.getMembershipType(_member)];
}
/**
*@dev Gets long and short token addresses based on specified date
*@param _date
*@return short and long tokens' addresses
*/
function getTokens(uint _date) public view returns(address, address){
return(long_tokens[_date],short_tokens[_date]);
}
/**
*@dev Gets the type of Token (long and short token) for the specifed
*token address
*@param _token address
*@return token type short = 1 and long = 2
*/
function getTokenType(address _token) public view returns(uint){
return(token_type[_token]);
}
/**
*@dev Updates the fee amount
*@param _fee is the new fee amount
*/
function setFee(uint _fee) public onlyOwner() {
fee = _fee;
}
/**
*@dev Updates the swap fee amount
*@param _swapFee is the new swap fee amount
*/
function setSwapFee(uint _swapFee) public onlyOwner() {
swapFee = _swapFee;
}
/**
*@dev Sets the deployer address
*@param _deployer is the new deployer address
*/
function setDeployer(address _deployer) public onlyOwner() {
deployer_address = _deployer;
deployer = Deployer_Interface(_deployer);
}
/**
*@dev Sets the user_contract address
*@param _userContract is the new userContract address
*/
function setUserContract(address _userContract) public onlyOwner() {
user_contract = _userContract;
}
/**
*@dev Sets token ratio, swap duration, and multiplier variables for a swap.
*@param _token_ratio the ratio of the tokens
*@param _duration the duration of the swap, in days
*@param _multiplier the multiplier used for the swap
*@param _swapFee the swap fee
*/
function setVariables(uint _token_ratio, uint _duration, uint _multiplier, uint _swapFee) public onlyOwner() {
require(_swapFee < 10000);
token_ratio = _token_ratio;
duration = _duration;
multiplier = _multiplier;
swapFee = _swapFee;
}
/**
*@dev Sets the address of the base tokens used for the swap
*@param _token The address of a token to be used as collateral
*/
function setBaseToken(address _token) public onlyOwner() {
token = _token;
}
/**
*@dev Allows a user to deploy a new swap contract, if they pay the fee
*@param _start_date the contract start date
*@return new_contract address for he newly created swap address and calls
*event 'ContractCreation'
*/
function deployContract(uint _start_date) public payable returns (address) {
require(msg.value >= fee && isWhitelisted(msg.sender));
require(_start_date % 86400 == 0);
address new_contract = deployer.newContract(msg.sender, user_contract, _start_date);
contracts.push(new_contract);
created_contracts[new_contract] = _start_date;
emit ContractCreation(msg.sender,new_contract);
return new_contract;
}
/**
*@dev Deploys DRCT tokens for given start date
*@param _start_date of contract
*/
function deployTokenContract(uint _start_date) public{
address _token;
require(_start_date % 86400 == 0);
require(long_tokens[_start_date] == address(0) && short_tokens[_start_date] == address(0));
_token = new DRCT_Token();
token_dates[_token] = _start_date;
long_tokens[_start_date] = _token;
token_type[_token]=2;
_token = new DRCT_Token();
token_type[_token]=1;
short_tokens[_start_date] = _token;
token_dates[_token] = _start_date;
startDates.push(_start_date);
}
/**
*@dev Deploys new tokens on a DRCT_Token contract -- called from within a swap
*@param _supply The number of tokens to create
*@param _party the address to send the tokens to
*@param _start_date the start date of the contract
*@returns ltoken the address of the created DRCT long tokens
*@returns stoken the address of the created DRCT short tokens
*@returns token_ratio The ratio of the created DRCT token
*/
function createToken(uint _supply, address _party, uint _start_date) public returns (address, address, uint) {
require(created_contracts[msg.sender] == _start_date);
address ltoken = long_tokens[_start_date];
address stoken = short_tokens[_start_date];
require(ltoken != address(0) && stoken != address(0));
DRCT_Token drct_interface = DRCT_Token(ltoken);
drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);
drct_interface = DRCT_Token(stoken);
drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);
return (ltoken, stoken, token_ratio);
}
/**
*@dev Allows the owner to set a new oracle address
*@param _new_oracle_address
*/
function setOracleAddress(address _new_oracle_address) public onlyOwner() {
oracle_address = _new_oracle_address;
}
/**
*@dev Allows the owner to set a new owner address
*@param _new_owner the new owner address
*/
function setOwner(address _new_owner) public onlyOwner() {
owner = _new_owner;
}
/**
*@dev Allows the owner to pull contract creation fees
*@return the withdrawal fee _val and the balance where is the return function?
*/
function withdrawFees() public onlyOwner(){
Wrapped_Ether_Interface token_interface = Wrapped_Ether_Interface(token);
uint _val = token_interface.balanceOf(address(this));
if(_val > 0){
token_interface.withdraw(_val);
}
owner.transfer(address(this).balance);
}
/**
*@dev fallback function
*/
function() public payable {
}
/**
*@dev Returns a tuple of many private variables.
*The variables from this function are pass through to the TokenLibrary.getVariables function
*@returns oracle_adress is the address of the oracle
*@returns duration is the duration of the swap
*@returns multiplier is the multiplier for the swap
*@returns token is the address of token
*@returns _swapFee is the swap fee
*/
function getVariables() public view returns (address, uint, uint, address,uint){
return (oracle_address,duration, multiplier, token,swapFee);
}
/**
*@dev Pays out to a DRCT token
*@param _party is the address being paid
*@param _token_add token to pay out
*/
function payToken(address _party, address _token_add) public {
require(created_contracts[msg.sender] > 0);
DRCT_Token drct_interface = DRCT_Token(_token_add);
drct_interface.pay(_party, msg.sender);
}
/**
*@dev Counts number of contacts created by this factory
*@return the number of contracts
*/
function getCount() public constant returns(uint) {
return contracts.length;
}
/**
*@dev Counts number of start dates in this factory
*@return the number of active start dates
*/
function getDateCount() public constant returns(uint) {
return startDates.length;
}
}
/**
*This contracts helps clone factories and swaps through the Deployer.sol and MasterDeployer.sol.
*The address of the targeted contract to clone has to be provided.
*/
contract CloneFactory {
/*Variables*/
address internal owner;
/*Events*/
event CloneCreated(address indexed target, address clone);
/*Modifiers*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*Functions*/
constructor() public{
owner = msg.sender;
}
/**
*@dev Allows the owner to set a new owner address
*@param _owner the new owner address
*/
function setOwner(address _owner) public onlyOwner(){
owner = _owner;
}
/**
*@dev Creates factory clone
*@param _target is the address being cloned
*@return address for clone
*/
function createClone(address target) internal returns (address result) {
bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd";
bytes20 targetBytes = bytes20(target);
for (uint i = 0; i < 20; i++) {
clone[26 + i] = targetBytes[i];
}
assembly {
let len := mload(clone)
let data := add(clone, 0x20)
result := create(0, data, len)
}
}
}
/**
*This contract deploys a factory contract and uses CloneFactory to clone the factory
*specified.
*/
contract MasterDeployer is CloneFactory{
using SafeMath for uint256;
/*Variables*/
address[] factory_contracts;
address private factory;
mapping(address => uint) public factory_index;
/*Events*/
event NewFactory(address _factory);
/*Functions*/
/**
*@dev Initiates the factory_contract array with address(0)
*/
constructor() public {
factory_contracts.push(address(0));
}
/**
*@dev Set factory address to clone
*@param _factory address to clone
*/
function setFactory(address _factory) public onlyOwner(){
factory = _factory;
}
/**
*@dev creates a new factory by cloning the factory specified in setFactory.
*@return _new_fac which is the new factory address
*/
function deployFactory() public onlyOwner() returns(address){
address _new_fac = createClone(factory);
factory_index[_new_fac] = factory_contracts.length;
factory_contracts.push(_new_fac);
Factory(_new_fac).init(msg.sender);
emit NewFactory(_new_fac);
return _new_fac;
}
/**
*@dev Removes the factory specified
*@param _factory address to remove
*/
function removeFactory(address _factory) public onlyOwner(){
require(_factory != address(0) && factory_index[_factory] != 0);
uint256 fIndex = factory_index[_factory];
uint256 lastFactoryIndex = factory_contracts.length.sub(1);
address lastFactory = factory_contracts[lastFactoryIndex];
factory_contracts[fIndex] = lastFactory;
factory_index[lastFactory] = fIndex;
factory_contracts.length--;
factory_index[_factory] = 0;
}
/**
*@dev Counts the number of factories
*@returns the number of active factories
*/
function getFactoryCount() public constant returns(uint){
return factory_contracts.length - 1;
}
/**
*@dev Returns the factory address for the specified index
*@param _index for factory to look up in the factory_contracts array
*@return factory address for the index specified
*/
function getFactorybyIndex(uint _index) public constant returns(address){
return factory_contracts[_index];
}
} | *@dev Gets the type of Token (long and short token) for the specifedtoken address@param _token address@return token type short = 1 and long = 2/ | function getTokenType(address _token) public view returns(uint){
return(token_type[_token]);
}
| 2,080,665 | [
1,
3002,
326,
618,
434,
3155,
261,
5748,
471,
3025,
1147,
13,
364,
326,
857,
430,
329,
2316,
1758,
389,
2316,
1758,
2463,
1147,
618,
3025,
273,
404,
471,
1525,
273,
576,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9162,
559,
12,
2867,
389,
2316,
13,
1071,
1476,
1135,
12,
11890,
15329,
203,
3639,
327,
12,
2316,
67,
723,
63,
67,
2316,
19226,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.10;
contract EthVault {
mapping (address => uint256) internal vault;
/// @dev Store ether in the contract.
function deposit() public payable {
vault[msg.sender] += msg.value;
}
/// @dev Release ether stored in the contract to a recipient.
/// @param recipient Who to send the tokens to.
function release(address payable recipient) public {
uint256 amount = vault[msg.sender];
delete vault[msg.sender];
recipient.transfer(amount);
}
} | @dev Store ether in the contract. | function deposit() public payable {
vault[msg.sender] += msg.value;
}
| 2,559,491 | [
1,
2257,
225,
2437,
316,
326,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
443,
1724,
1435,
1071,
8843,
429,
288,
203,
3639,
9229,
63,
3576,
18,
15330,
65,
1011,
1234,
18,
1132,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x17D68bC85eb5DF6631295693E587dbBB820c752F/sources/contracts/PoolFactory.sol | * @inheritdoc IPoolFactory/ | function isPool(address pool) external view returns (bool) {
return _pools.contains(pool);
}
| 4,819,767 | [
1,
36,
10093,
467,
2864,
1733,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
353,
2864,
12,
2867,
2845,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
27663,
18,
12298,
12,
6011,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/100/0xB15bED5B56A33fbd6BCcC816cB0B38642Fba5FDD/sources/contracts/NFBeez.sol | eventsEmit event on royalty Epor.io | contract OneHiveTVElk is ERC721Enumerable, Ownable, HasSecondarySaleFees {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
uint256 public cost = 10000 ether;
uint256 public maxSupply = 5;
uint256 public maxMintAmount = 5;
uint256 public nftPerAddressLimit = 1;
bool public paused = false;
bool public revealed = false;
bool public onlyWhitelisted = true;
address[] public whitelistedAddresses;
address payable[2] royaltyRecipients;
mapping(address => uint256) public addressMintedBalance;
event MintedNFT(address sender, uint256 mintAmount, uint256 _nftId);
event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps);
constructor(string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri, address payable[2] memory _royaltyRecipients)
ERC721(_name, _symbol)
HasSecondarySaleFees(new address payable[](0), new uint256[](0)) payable {
require(_royaltyRecipients[0] != address(0), "Invalid address");
require(_royaltyRecipients[1] != address(0), "Invalid address");
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
royaltyRecipients = _royaltyRecipients;
address payable[] memory thisAddressInArray = new address payable[](1);
thisAddressInArray[0] = payable(_royaltyRecipients[0]);
uint256[] memory royaltyWithTwoDecimals = new uint256[](1);
royaltyWithTwoDecimals[0] = 500;
_setCommonRoyalties(thisAddressInArray, royaltyWithTwoDecimals);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, HasSecondarySaleFees)
returns (bool)
{
return ERC721.supportsInterface(interfaceId) ||
HasSecondarySaleFees.supportsInterface(interfaceId);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
if(onlyWhitelisted == true) {
require(isWhitelisted(msg.sender), "user is not whitelisted");
uint256 ownerMintedCount = addressMintedBalance[msg.sender];
require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded");
}
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
emit MintedNFT(msg.sender, _mintAmount, supply + i);
}
}
function mint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
if(onlyWhitelisted == true) {
require(isWhitelisted(msg.sender), "user is not whitelisted");
uint256 ownerMintedCount = addressMintedBalance[msg.sender];
require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded");
}
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
emit MintedNFT(msg.sender, _mintAmount, supply + i);
}
}
function mint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
if(onlyWhitelisted == true) {
require(isWhitelisted(msg.sender), "user is not whitelisted");
uint256 ownerMintedCount = addressMintedBalance[msg.sender];
require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded");
}
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
emit MintedNFT(msg.sender, _mintAmount, supply + i);
}
}
function mint(uint256 _mintAmount) public payable {
require(!paused, "the contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
if(onlyWhitelisted == true) {
require(isWhitelisted(msg.sender), "user is not whitelisted");
uint256 ownerMintedCount = addressMintedBalance[msg.sender];
require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded");
}
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
emit MintedNFT(msg.sender, _mintAmount, supply + i);
}
}
function isWhitelisted(address _user) public view returns (bool) {
for (uint i = 0; i < whitelistedAddresses.length; i++) {
if (whitelistedAddresses[i] == _user) {
return true;
}
}
return false;
}
function isWhitelisted(address _user) public view returns (bool) {
for (uint i = 0; i < whitelistedAddresses.length; i++) {
if (whitelistedAddresses[i] == _user) {
return true;
}
}
return false;
}
function isWhitelisted(address _user) public view returns (bool) {
for (uint i = 0; i < whitelistedAddresses.length; i++) {
if (whitelistedAddresses[i] == _user) {
return true;
}
}
return false;
}
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
function reveal() public onlyOwner() {
revealed = true;
}
function setNftPerAddressLimit(uint256 _limit) public onlyOwner() {
nftPerAddressLimit = _limit;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setOnlyWhitelisted(bool _state) public onlyOwner {
onlyWhitelisted = _state;
}
function whitelistUsers(address[] calldata _users) public onlyOwner {
delete whitelistedAddresses;
whitelistedAddresses = _users;
}
function withdraw() public payable onlyOwner {
require(success);
}
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
} | 14,286,985 | [
1,
5989,
17982,
871,
603,
721,
93,
15006,
512,
3831,
18,
1594,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
6942,
44,
688,
56,
3412,
80,
79,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
16,
4393,
14893,
30746,
2954,
281,
288,
203,
225,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
225,
533,
1071,
1026,
3098,
31,
203,
225,
533,
1071,
1026,
3625,
273,
3552,
1977,
14432,
203,
225,
533,
1071,
486,
426,
537,
18931,
3006,
31,
203,
225,
2254,
5034,
1071,
6991,
273,
12619,
225,
2437,
31,
21281,
225,
2254,
5034,
1071,
943,
3088,
1283,
273,
1381,
31,
21281,
225,
2254,
5034,
1071,
943,
49,
474,
6275,
273,
1381,
31,
7010,
225,
2254,
5034,
1071,
290,
1222,
2173,
1887,
3039,
273,
404,
31,
203,
225,
1426,
1071,
17781,
273,
629,
31,
203,
225,
1426,
1071,
283,
537,
18931,
273,
629,
31,
203,
225,
1426,
1071,
1338,
18927,
329,
273,
638,
31,
203,
225,
1758,
8526,
1071,
26944,
7148,
31,
203,
225,
1758,
8843,
429,
63,
22,
65,
721,
93,
15006,
22740,
31,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
1758,
49,
474,
329,
13937,
31,
203,
203,
7010,
225,
871,
490,
474,
329,
50,
4464,
12,
2867,
5793,
16,
2254,
5034,
312,
474,
6275,
16,
2254,
5034,
389,
82,
1222,
548,
1769,
203,
225,
871,
30983,
30746,
2954,
281,
12,
11890,
5034,
1147,
548,
16,
1758,
8526,
12045,
16,
2254,
8526,
324,
1121,
1769,
203,
203,
225,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
16,
533,
3778,
389,
2738,
2171,
3098,
16,
533,
3778,
389,
2738,
1248,
426,
537,
18931,
3006,
16,
2
]
|
//Address: 0x162e8ff9d5bc3112fb3b2dec0580a4011f3cc622
//Contract name: MetropolCrowdsale
//Balance: 0 Ether
//Verification Date: 12/1/2017
//Transacion Count: 7
// CODE STARTS HERE
pragma solidity ^0.4.18;
/// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled
// TODO acceptOwnership
contract multiowned {
// TYPES
// struct for the status of a pending operation.
struct MultiOwnedOperationPendingState {
// count of confirmations needed
uint yetNeeded;
// bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit
uint ownersDone;
// position of this operation key in m_multiOwnedPendingIndex
uint index;
}
// EVENTS
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
event FinalConfirmation(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
require(isOwner(msg.sender));
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
// Even if required number of confirmations has't been collected yet,
// we can't throw here - because changes to the state have to be preserved.
// But, confirmAndCheck itself will throw in case sender is not an owner.
}
modifier validNumOwners(uint _numOwners) {
require(_numOwners > 0 && _numOwners <= c_maxOwners);
_;
}
modifier multiOwnedValidRequirement(uint _required, uint _numOwners) {
require(_required > 0 && _required <= _numOwners);
_;
}
modifier ownerExists(address _address) {
require(isOwner(_address));
_;
}
modifier ownerDoesNotExist(address _address) {
require(!isOwner(_address));
_;
}
modifier multiOwnedOperationIsActive(bytes32 _operation) {
require(isOperationActive(_operation));
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!).
function multiowned(address[] _owners, uint _required)
validNumOwners(_owners.length)
multiOwnedValidRequirement(_required, _owners.length)
{
assert(c_maxOwners <= 255);
m_numOwners = _owners.length;
m_multiOwnedRequired = _required;
for (uint i = 0; i < _owners.length; ++i)
{
address owner = _owners[i];
// invalid and duplicate addresses are not allowed
require(0 != owner && !isOwner(owner) /* not isOwner yet! */);
uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */);
m_owners[currentOwnerIndex] = owner;
m_ownerIndex[owner] = currentOwnerIndex;
}
assertOwnersAreConsistent();
}
/// @notice replaces an owner `_from` with another `_to`.
/// @param _from address of owner to replace
/// @param _to address of new owner
// All pending operations will be canceled!
function changeOwner(address _from, address _to)
external
ownerExists(_from)
ownerDoesNotExist(_to)
onlymanyowners(sha3(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]);
m_owners[ownerIndex] = _to;
m_ownerIndex[_from] = 0;
m_ownerIndex[_to] = ownerIndex;
assertOwnersAreConsistent();
OwnerChanged(_from, _to);
}
/// @notice adds an owner
/// @param _owner address of new owner
// All pending operations will be canceled!
function addOwner(address _owner)
external
ownerDoesNotExist(_owner)
validNumOwners(m_numOwners + 1)
onlymanyowners(sha3(msg.data))
{
assertOwnersAreConsistent();
clearPending();
m_numOwners++;
m_owners[m_numOwners] = _owner;
m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners);
assertOwnersAreConsistent();
OwnerAdded(_owner);
}
/// @notice removes an owner
/// @param _owner address of owner to remove
// All pending operations will be canceled!
function removeOwner(address _owner)
external
ownerExists(_owner)
validNumOwners(m_numOwners - 1)
multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1)
onlymanyowners(sha3(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]);
m_owners[ownerIndex] = 0;
m_ownerIndex[_owner] = 0;
//make sure m_numOwners is equal to the number of owners and always points to the last owner
reorganizeOwners();
assertOwnersAreConsistent();
OwnerRemoved(_owner);
}
/// @notice changes the required number of owner signatures
/// @param _newRequired new number of signatures required
// All pending operations will be canceled!
function changeRequirement(uint _newRequired)
external
multiOwnedValidRequirement(_newRequired, m_numOwners)
onlymanyowners(sha3(msg.data))
{
m_multiOwnedRequired = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
/// @notice Gets an owner by 0-indexed position
/// @param ownerIndex 0-indexed owner position
function getOwner(uint ownerIndex) public constant returns (address) {
return m_owners[ownerIndex + 1];
}
/// @notice Gets owners
/// @return memory array of owners
function getOwners() public constant returns (address[]) {
address[] memory result = new address[](m_numOwners);
for (uint i = 0; i < m_numOwners; i++)
result[i] = getOwner(i);
return result;
}
/// @notice checks if provided address is an owner address
/// @param _addr address to check
/// @return true if it's an owner
function isOwner(address _addr) public constant returns (bool) {
return m_ownerIndex[_addr] > 0;
}
/// @notice Tests ownership of the current caller.
/// @return true if it's an owner
// It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to
// addOwner/changeOwner and to isOwner.
function amIOwner() external constant onlyowner returns (bool) {
return true;
}
/// @notice Revokes a prior confirmation of the given operation
/// @param _operation operation value, typically sha3(msg.data)
function revoke(bytes32 _operation)
external
multiOwnedOperationIsActive(_operation)
onlyowner
{
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
var pending = m_multiOwnedPending[_operation];
require(pending.ownersDone & ownerIndexBit > 0);
assertOperationIsConsistent(_operation);
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
assertOperationIsConsistent(_operation);
Revoke(msg.sender, _operation);
}
/// @notice Checks if owner confirmed given operation
/// @param _operation operation value, typically sha3(msg.data)
/// @param _owner an owner address
function hasConfirmed(bytes32 _operation, address _owner)
external
constant
multiOwnedOperationIsActive(_operation)
ownerExists(_owner)
returns (bool)
{
return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation)
private
onlyowner
returns (bool)
{
if (512 == m_multiOwnedPendingIndex.length)
// In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point
// we won't be able to do it because of block gas limit.
// Yes, pending confirmations will be lost. Dont see any security or stability implications.
// TODO use more graceful approach like compact or removal of clearPending completely
clearPending();
var pending = m_multiOwnedPending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (! isOperationActive(_operation)) {
// reset count of confirmations needed.
pending.yetNeeded = m_multiOwnedRequired;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_multiOwnedPendingIndex.length++;
m_multiOwnedPendingIndex[pending.index] = _operation;
assertOperationIsConsistent(_operation);
}
// determine the bit to set for this owner.
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
// ok - check if count is enough to go ahead.
assert(pending.yetNeeded > 0);
if (pending.yetNeeded == 1) {
// enough confirmations: reset and run interior.
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index];
delete m_multiOwnedPending[_operation];
FinalConfirmation(msg.sender, _operation);
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
assertOperationIsConsistent(_operation);
Confirmation(msg.sender, _operation);
}
}
}
// Reclaims free slots between valid owners in m_owners.
// TODO given that its called after each removal, it could be simplified.
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
// iterating to the first free slot from the beginning
while (free < m_numOwners && m_owners[free] != 0) free++;
// iterating to the first occupied slot from the end
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
// swap, if possible, so free slot is located at the end after the swap
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
// owners between swapped slots should't be renumbered - that saves a lot of gas
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() private onlyowner {
uint length = m_multiOwnedPendingIndex.length;
// TODO block gas limit
for (uint i = 0; i < length; ++i) {
if (m_multiOwnedPendingIndex[i] != 0)
delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]];
}
delete m_multiOwnedPendingIndex;
}
function checkOwnerIndex(uint ownerIndex) private constant returns (uint) {
assert(0 != ownerIndex && ownerIndex <= c_maxOwners);
return ownerIndex;
}
function makeOwnerBitmapBit(address owner) private constant returns (uint) {
uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]);
return 2 ** ownerIndex;
}
function isOperationActive(bytes32 _operation) private constant returns (bool) {
return 0 != m_multiOwnedPending[_operation].yetNeeded;
}
function assertOwnersAreConsistent() private constant {
assert(m_numOwners > 0);
assert(m_numOwners <= c_maxOwners);
assert(m_owners[0] == 0);
assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners);
}
function assertOperationIsConsistent(bytes32 _operation) private constant {
var pending = m_multiOwnedPending[_operation];
assert(0 != pending.yetNeeded);
assert(m_multiOwnedPendingIndex[pending.index] == _operation);
assert(pending.yetNeeded <= m_multiOwnedRequired);
}
// FIELDS
uint constant c_maxOwners = 250;
// the number of owners that must confirm the same operation before it is run.
uint public m_multiOwnedRequired;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners (addresses),
// slot 0 is unused so there are no owner which index is 0.
// TODO could we save space at the end of the array for the common case of <10 owners? and should we?
address[256] internal m_owners;
// index on the list of owners to allow reverse lookup: owner address => index in m_owners
mapping(address => uint) internal m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending;
bytes32[] internal m_multiOwnedPendingIndex;
}
/**
* @title Helps contracts guard agains rentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
}
/**
* @title Contract which is owned by owners and operated by controller.
*
* @notice Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
* Controller is set up by owners or during construction.
*
* @dev controller check is performed by onlyController modifier.
*/
contract MultiownedControlled is multiowned {
event ControllerSet(address controller);
event ControllerRetired(address was);
modifier onlyController {
require(msg.sender == m_controller);
_;
}
// PUBLIC interface
function MultiownedControlled(address[] _owners, uint _signaturesRequired, address _controller)
multiowned(_owners, _signaturesRequired)
{
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev sets the controller
function setController(address _controller) external onlymanyowners(sha3(msg.data)) {
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev ability for controller to step down
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
// FIELDS
/// @notice address of entity entitled to mint new tokens
address public m_controller;
}
/// @title utility methods and modifiers of arguments validation
contract ArgumentsChecker {
/// @dev check which prevents short address attack
modifier payloadSizeIs(uint size) {
require(msg.data.length == size + 4 /* function selector */);
_;
}
/// @dev check that address is valid
modifier validAddress(address addr) {
require(addr != address(0));
_;
}
}
/// @title registry of funds sent by investors
contract FundsRegistry is ArgumentsChecker, MultiownedControlled, ReentrancyGuard {
using SafeMath for uint256;
enum State {
// gathering funds
GATHERING,
// returning funds to investors
REFUNDING,
// funds can be pulled by owners
SUCCEEDED
}
event StateChanged(State _state);
event Invested(address indexed investor, uint256 amount);
event EtherSent(address indexed to, uint value);
event RefundSent(address indexed to, uint value);
modifier requiresState(State _state) {
require(m_state == _state);
_;
}
// PUBLIC interface
function FundsRegistry(address[] _owners, uint _signaturesRequired, address _controller)
MultiownedControlled(_owners, _signaturesRequired, _controller)
{
}
/// @dev performs only allowed state transitions
function changeState(State _newState)
external
onlyController
{
assert(m_state != _newState);
if (State.GATHERING == m_state) { assert(State.REFUNDING == _newState || State.SUCCEEDED == _newState); }
else assert(false);
m_state = _newState;
StateChanged(m_state);
}
/// @dev records an investment
function invested(address _investor)
external
payable
onlyController
requiresState(State.GATHERING)
{
uint256 amount = msg.value;
require(0 != amount);
assert(_investor != m_controller);
// register investor
if (0 == m_weiBalances[_investor])
m_investors.push(_investor);
// register payment
totalInvested = totalInvested.add(amount);
m_weiBalances[_investor] = m_weiBalances[_investor].add(amount);
Invested(_investor, amount);
}
/// @notice owners: send `value` of ether to address `to`, can be called if crowdsale succeeded
/// @param to where to send ether
/// @param value amount of wei to send
function sendEther(address to, uint value)
external
validAddress(to)
onlymanyowners(sha3(msg.data))
requiresState(State.SUCCEEDED)
{
require(value > 0 && this.balance >= value);
to.transfer(value);
EtherSent(to, value);
}
/// @notice withdraw accumulated balance, called by payee in case crowdsale failed
function withdrawPayments(address payee)
external
nonReentrant
onlyController
requiresState(State.REFUNDING)
{
uint256 payment = m_weiBalances[payee];
require(payment != 0);
require(this.balance >= payment);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
payee.transfer(payment);
RefundSent(payee, payment);
}
function getInvestorsCount() external constant returns (uint) { return m_investors.length; }
// FIELDS
/// @notice total amount of investments in wei
uint256 public totalInvested;
/// @notice state of the registry
State public m_state = State.GATHERING;
/// @dev balances of investors in wei
mapping(address => uint256) public m_weiBalances;
/// @dev list of unique investors
address[] public m_investors;
}
///123
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/// @title StandardToken which can be minted by another contract.
contract MintableToken {
event Mint(address indexed to, uint256 amount);
/// @dev mints new tokens
function mint(address _to, uint256 _amount) public;
}
/**
* MetropolMintableToken
*/
contract MetropolMintableToken is StandardToken, MintableToken {
event Mint(address indexed to, uint256 amount);
function mint(address _to, uint256 _amount) public;//todo propose return value
/**
* Function to mint tokens
* Internal for not forgetting to add access modifier
*
* @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 mintInternal(address _to, uint256 _amount) internal returns (bool) {
require(_amount>0);
require(_to!=address(0));
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
}
/**
* Contract which is operated by controller.
*
* Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
*
* Controller check is performed by onlyController modifier.
*/
contract Controlled {
address public m_controller;
event ControllerSet(address controller);
event ControllerRetired(address was);
modifier onlyController {
require(msg.sender == m_controller);
_;
}
function setController(address _controller) external;
/**
* Sets the controller. Internal for not forgetting to add access modifier
*/
function setControllerInternal(address _controller) internal {
m_controller = _controller;
ControllerSet(m_controller);
}
/**
* Ability for controller to step down
*/
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
}
/**
* MintableControlledToken
*/
contract MintableControlledToken is MetropolMintableToken, Controlled {
/**
* 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 onlyController {
super.mintInternal(_to, _amount);
}
}
/**
* BurnableToken
*/
contract BurnableToken is StandardToken {
event Burn(address indexed from, uint256 amount);
function burn(address _from, uint256 _amount) public returns (bool);
/**
* Function to burn tokens
* Internal for not forgetting to add access modifier
*
* @param _from The address to burn tokens from.
* @param _amount The amount of tokens to burn.
*
* @return A boolean that indicates if the operation was successful.
*/
function burnInternal(address _from, uint256 _amount) internal returns (bool) {
require(_amount>0);
require(_amount<=balances[_from]);
totalSupply = totalSupply.sub(_amount);
balances[_from] = balances[_from].sub(_amount);
Burn(_from, _amount);
Transfer(_from, address(0), _amount);
return true;
}
}
/**
* BurnableControlledToken
*/
contract BurnableControlledToken is BurnableToken, Controlled {
/**
* Function to burn tokens
*
* @param _from The address to burn tokens from.
* @param _amount The amount of tokens to burn.
*
* @return A boolean that indicates if the operation was successful.
*/
function burn(address _from, uint256 _amount) public onlyController returns (bool) {
return super.burnInternal(_from, _amount);
}
}
/**
* Contract which is owned by owners and operated by controller.
*
* Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
* Controller is set up by owners or during construction.
*
*/
contract MetropolMultiownedControlled is Controlled, multiowned {
function MetropolMultiownedControlled(address[] _owners, uint256 _signaturesRequired)
multiowned(_owners, _signaturesRequired)
public
{
// nothing here
}
/**
* Sets the controller
*/
function setController(address _controller) external onlymanyowners(sha3(msg.data)) {
super.setControllerInternal(_controller);
}
}
/// @title StandardToken which circulation can be delayed and started by another contract.
/// @dev To be used as a mixin contract.
/// The contract is created in disabled state: circulation is disabled.
contract CirculatingToken is StandardToken {
event CirculationEnabled();
modifier requiresCirculation {
require(m_isCirculating);
_;
}
// PUBLIC interface
function transfer(address _to, uint256 _value) requiresCirculation returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) requiresCirculation returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) requiresCirculation returns (bool) {
return super.approve(_spender, _value);
}
// INTERNAL functions
function enableCirculation() internal returns (bool) {
if (m_isCirculating)
return false;
m_isCirculating = true;
CirculationEnabled();
return true;
}
// FIELDS
/// @notice are the circulation started?
bool public m_isCirculating;
}
/**
* CirculatingControlledToken
*/
contract CirculatingControlledToken is CirculatingToken, Controlled {
/**
* Allows token transfers
*/
function startCirculation() external onlyController {
assert(enableCirculation()); // must be called once
}
}
/**
* MetropolToken
*/
contract MetropolToken is
StandardToken,
Controlled,
MintableControlledToken,
BurnableControlledToken,
CirculatingControlledToken,
MetropolMultiownedControlled
{
string internal m_name = '';
string internal m_symbol = '';
uint8 public constant decimals = 18;
/**
* MetropolToken constructor
*/
function MetropolToken(address[] _owners)
MetropolMultiownedControlled(_owners, 2)
public
{
require(3 == _owners.length);
}
function name() public constant returns (string) {
return m_name;
}
function symbol() public constant returns (string) {
return m_symbol;
}
function setNameSymbol(string _name, string _symbol) external onlymanyowners(sha3(msg.data)) {
require(bytes(m_name).length==0);
require(bytes(_name).length!=0 && bytes(_symbol).length!=0);
m_name = _name;
m_symbol = _symbol;
}
}
/////////123
/**
* @title Basic crowdsale stat
* @author Eenae
*/
contract ICrowdsaleStat {
/// @notice amount of funds collected in wei
function getWeiCollected() public constant returns (uint);
/// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!)
function getTokenMinted() public constant returns (uint);
}
/**
* @title Interface for code which processes and stores investments.
* @author Eenae
*/
contract IInvestmentsWalletConnector {
/// @dev process and forward investment
function storeInvestment(address investor, uint payment) internal;
/// @dev total investments amount stored using storeInvestment()
function getTotalInvestmentsStored() internal constant returns (uint);
/// @dev called in case crowdsale succeeded
function wcOnCrowdsaleSuccess() internal;
/// @dev called in case crowdsale failed
function wcOnCrowdsaleFailure() internal;
}
/// @title Base contract for simple crowdsales
contract SimpleCrowdsaleBase is ArgumentsChecker, ReentrancyGuard, IInvestmentsWalletConnector, ICrowdsaleStat {
using SafeMath for uint256;
event FundTransfer(address backer, uint amount, bool isContribution);
function SimpleCrowdsaleBase(address token)
validAddress(token)
{
m_token = MintableToken(token);
}
// PUBLIC interface: payments
// fallback function as a shortcut
function() payable {
require(0 == msg.data.length);
buy(); // only internal call here!
}
/// @notice crowdsale participation
function buy() public payable { // dont mark as external!
buyInternal(msg.sender, msg.value, 0);
}
// INTERNAL
/// @dev payment processing
function buyInternal(address investor, uint payment, uint extraBonuses)
internal
nonReentrant
{
require(payment >= getMinInvestment());
require(getCurrentTime() >= getStartTime() || ! mustApplyTimeCheck(investor, payment) /* for final check */);
if (getCurrentTime() >= getEndTime()) {
finish();
}
if (m_finished) {
// saving provided gas
investor.transfer(payment);
return;
}
uint startingWeiCollected = getWeiCollected();
uint startingInvariant = this.balance.add(startingWeiCollected);
uint change;
if (hasHardCap()) {
// return or update payment if needed
uint paymentAllowed = getMaximumFunds().sub(getWeiCollected());
assert(0 != paymentAllowed);
if (paymentAllowed < payment) {
change = payment.sub(paymentAllowed);
payment = paymentAllowed;
}
}
// issue tokens
uint tokens = calculateTokens(investor, payment, extraBonuses);
m_token.mint(investor, tokens);
m_tokensMinted += tokens;
// record payment
storeInvestment(investor, payment);
assert((!hasHardCap() || getWeiCollected() <= getMaximumFunds()) && getWeiCollected() > startingWeiCollected);
FundTransfer(investor, payment, true);
if (hasHardCap() && getWeiCollected() == getMaximumFunds())
finish();
if (change > 0)
investor.transfer(change);
assert(startingInvariant == this.balance.add(getWeiCollected()).add(change));
}
function finish() internal {
if (m_finished)
return;
if (getWeiCollected() >= getMinimumFunds())
wcOnCrowdsaleSuccess();
else
wcOnCrowdsaleFailure();
m_finished = true;
}
// Other pluggables
/// @dev says if crowdsale time bounds must be checked
function mustApplyTimeCheck(address /*investor*/, uint /*payment*/) constant internal returns (bool) {
return true;
}
/// @notice whether to apply hard cap check logic via getMaximumFunds() method
function hasHardCap() constant internal returns (bool) {
return getMaximumFunds() != 0;
}
/// @dev to be overridden in tests
function getCurrentTime() internal constant returns (uint) {
return now;
}
/// @notice maximum investments to be accepted during pre-ICO
function getMaximumFunds() internal constant returns (uint);
/// @notice minimum amount of funding to consider crowdsale as successful
function getMinimumFunds() internal constant returns (uint);
/// @notice start time of the pre-ICO
function getStartTime() internal constant returns (uint);
/// @notice end time of the pre-ICO
function getEndTime() internal constant returns (uint);
/// @notice minimal amount of investment
function getMinInvestment() public constant returns (uint) {
return 10 finney;
}
/// @dev calculates token amount for given investment
function calculateTokens(address investor, uint payment, uint extraBonuses) internal constant returns (uint);
// ICrowdsaleStat
function getWeiCollected() public constant returns (uint) {
return getTotalInvestmentsStored();
}
/// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!)
function getTokenMinted() public constant returns (uint) {
return m_tokensMinted;
}
// FIELDS
/// @dev contract responsible for token accounting
MintableToken public m_token;
uint m_tokensMinted;
bool m_finished = false;
}
/// @title Stateful mixin add state to contact and handlers for it
contract SimpleStateful {
enum State { INIT, RUNNING, PAUSED, FAILED, SUCCEEDED }
event StateChanged(State _state);
modifier requiresState(State _state) {
require(m_state == _state);
_;
}
modifier exceptState(State _state) {
require(m_state != _state);
_;
}
function changeState(State _newState) internal {
assert(m_state != _newState);
if (State.INIT == m_state) {
assert(State.RUNNING == _newState);
}
else if (State.RUNNING == m_state) {
assert(State.PAUSED == _newState || State.FAILED == _newState || State.SUCCEEDED == _newState);
}
else if (State.PAUSED == m_state) {
assert(State.RUNNING == _newState || State.FAILED == _newState);
}
else assert(false);
m_state = _newState;
StateChanged(m_state);
}
function getCurrentState() internal view returns(State) {
return m_state;
}
/// @dev state of sale
State public m_state = State.INIT;
}
/**
* Stores investments in FundsRegistry.
*/
contract MetropolFundsRegistryWalletConnector is IInvestmentsWalletConnector {
function MetropolFundsRegistryWalletConnector(address _fundsAddress)
public
{
require(_fundsAddress!=address(0));
m_fundsAddress = FundsRegistry(_fundsAddress);
}
/// @dev process and forward investment
function storeInvestment(address investor, uint payment) internal
{
m_fundsAddress.invested.value(payment)(investor);
}
/// @dev total investments amount stored using storeInvestment()
function getTotalInvestmentsStored() internal constant returns (uint)
{
return m_fundsAddress.totalInvested();
}
/// @dev called in case crowdsale succeeded
function wcOnCrowdsaleSuccess() internal {
m_fundsAddress.changeState(FundsRegistry.State.SUCCEEDED);
m_fundsAddress.detachController();
}
/// @dev called in case crowdsale failed
function wcOnCrowdsaleFailure() internal {
m_fundsAddress.changeState(FundsRegistry.State.REFUNDING);
}
/// @notice address of wallet which stores funds
FundsRegistry public m_fundsAddress;
}
/**
* Crowdsale with state
*/
contract StatefulReturnableCrowdsale is
SimpleCrowdsaleBase,
SimpleStateful,
multiowned,
MetropolFundsRegistryWalletConnector
{
/** Last recorded funds */
uint256 public m_lastFundsAmount;
event Withdraw(address payee, uint amount);
/**
* Automatic check for unaccounted withdrawals
* @param _investor optional refund parameter
* @param _payment optional refund parameter
*/
modifier fundsChecker(address _investor, uint _payment) {
uint atTheBeginning = getTotalInvestmentsStored();
if (atTheBeginning < m_lastFundsAmount) {
changeState(State.PAUSED);
if (_payment > 0) {
_investor.transfer(_payment); // we cant throw (have to save state), so refunding this way
}
// note that execution of further (but not preceding!) modifiers and functions ends here
} else {
_;
if (getTotalInvestmentsStored() < atTheBeginning) {
changeState(State.PAUSED);
} else {
m_lastFundsAmount = getTotalInvestmentsStored();
}
}
}
/**
* Triggers some state changes based on current time
*/
modifier timedStateChange() {
if (getCurrentState() == State.INIT && getCurrentTime() >= getStartTime()) {
changeState(State.RUNNING);
}
_;
}
/**
* Constructor
*/
function StatefulReturnableCrowdsale(
address _token,
address _funds,
address[] _owners,
uint _signaturesRequired
)
public
SimpleCrowdsaleBase(_token)
multiowned(_owners, _signaturesRequired)
MetropolFundsRegistryWalletConnector(_funds)
validAddress(_token)
validAddress(_funds)
{
}
function pauseCrowdsale()
public
onlyowner
requiresState(State.RUNNING)
{
changeState(State.PAUSED);
}
function continueCrowdsale()
public
onlymanyowners(sha3(msg.data))
requiresState(State.PAUSED)
{
changeState(State.RUNNING);
if (getCurrentTime() >= getEndTime()) {
finish();
}
}
function failCrowdsale()
public
onlymanyowners(sha3(msg.data))
requiresState(State.PAUSED)
{
wcOnCrowdsaleFailure();
m_finished = true;
}
function withdrawPayments()
public
nonReentrant
requiresState(State.FAILED)
{
Withdraw(msg.sender, m_fundsAddress.m_weiBalances(msg.sender));
m_fundsAddress.withdrawPayments(msg.sender);
}
/**
* Additional check of contributing process since we have state
*/
function buyInternal(address _investor, uint _payment, uint _extraBonuses)
internal
timedStateChange
exceptState(State.PAUSED)
fundsChecker(_investor, _payment)
{
if (!mustApplyTimeCheck(_investor, _payment)) {
require(State.RUNNING == m_state || State.INIT == m_state);
}
else
{
require(State.RUNNING == m_state);
}
super.buyInternal(_investor, _payment, _extraBonuses);
}
/// @dev called in case crowdsale succeeded
function wcOnCrowdsaleSuccess() internal {
super.wcOnCrowdsaleSuccess();
changeState(State.SUCCEEDED);
}
/// @dev called in case crowdsale failed
function wcOnCrowdsaleFailure() internal {
super.wcOnCrowdsaleFailure();
changeState(State.FAILED);
}
}
/**
* MetropolCrowdsale
*/
contract MetropolCrowdsale is StatefulReturnableCrowdsale {
uint256 public m_startTimestamp;
uint256 public m_softCap;
uint256 public m_hardCap;
uint256 public m_exchangeRate;
address public m_foundersTokensStorage;
bool public m_initialSettingsSet = false;
modifier requireSettingsSet() {
require(m_initialSettingsSet);
_;
}
function MetropolCrowdsale(address _token, address _funds, address[] _owners)
public
StatefulReturnableCrowdsale(_token, _funds, _owners, 2)
{
require(3 == _owners.length);
//2030-01-01, not to start crowdsale
m_startTimestamp = 1893456000;
}
/**
* Set exchange rate before start
*/
function setInitialSettings(
address _foundersTokensStorage,
uint256 _startTimestamp,
uint256 _softCapInEther,
uint256 _hardCapInEther,
uint256 _tokensForOneEther
)
public
timedStateChange
requiresState(State.INIT)
onlymanyowners(sha3(msg.data))
validAddress(_foundersTokensStorage)
{
//no check for settings set
//can be set multiple times before ICO
require(_startTimestamp!=0);
require(_softCapInEther!=0);
require(_hardCapInEther!=0);
require(_tokensForOneEther!=0);
m_startTimestamp = _startTimestamp;
m_softCap = _softCapInEther * 1 ether;
m_hardCap = _hardCapInEther * 1 ether;
m_exchangeRate = _tokensForOneEther;
m_foundersTokensStorage = _foundersTokensStorage;
m_initialSettingsSet = true;
}
/**
* Set exchange rate before start
*/
function setExchangeRate(uint256 _tokensForOneEther)
public
timedStateChange
requiresState(State.INIT)
onlymanyowners(sha3(msg.data))
{
m_exchangeRate = _tokensForOneEther;
}
/**
* withdraw payments by investor on fail
*/
function withdrawPayments() public requireSettingsSet {
getToken().burn(
msg.sender,
getToken().balanceOf(msg.sender)
);
super.withdrawPayments();
}
// INTERNAL
/**
* Additional check of initial settings set
*/
function buyInternal(address _investor, uint _payment, uint _extraBonuses)
internal
requireSettingsSet
{
super.buyInternal(_investor, _payment, _extraBonuses);
}
/**
* All users except deployer must check time before contributing
*/
function mustApplyTimeCheck(address investor, uint payment) constant internal returns (bool) {
return !isOwner(investor);
}
/**
* For min investment check
*/
function getMinInvestment() public constant returns (uint) {
return 1 wei;
}
/**
* Get collected funds (internally from FundsRegistry)
*/
function getWeiCollected() public constant returns (uint) {
return getTotalInvestmentsStored();
}
/**
* Minimum amount of funding to consider crowdsale as successful
*/
function getMinimumFunds() internal constant returns (uint) {
return m_softCap;
}
/**
* Maximum investments to be accepted during crowdsale
*/
function getMaximumFunds() internal constant returns (uint) {
return m_hardCap;
}
/**
* Start time of the crowdsale
*/
function getStartTime() internal constant returns (uint) {
return m_startTimestamp;
}
/**
* End time of the crowdsale
*/
function getEndTime() internal constant returns (uint) {
return m_startTimestamp + 60 days;
}
/**
* Formula for calculating tokens from contributed ether
*/
function calculateTokens(address /*investor*/, uint payment, uint /*extraBonuses*/)
internal
constant
returns (uint)
{
uint256 secondMonth = m_startTimestamp + 30 days;
if (getCurrentTime() <= secondMonth) {
return payment.mul(m_exchangeRate);
} else if (getCurrentTime() <= secondMonth + 1 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(105);
} else if (getCurrentTime() <= secondMonth + 2 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(110);
} else if (getCurrentTime() <= secondMonth + 3 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(115);
} else if (getCurrentTime() <= secondMonth + 4 weeks) {
return payment.mul(m_exchangeRate).mul(100).div(120);
} else {
return payment.mul(m_exchangeRate).mul(100).div(125);
}
}
/**
* Additional on-success actions
*/
function wcOnCrowdsaleSuccess() internal {
super.wcOnCrowdsaleSuccess();
//20% of total totalSupply to team
m_token.mint(
m_foundersTokensStorage,
getToken().totalSupply().mul(20).div(80)
);
getToken().startCirculation();
getToken().detachController();
}
/**
* Returns attached token
*/
function getToken() internal returns(MetropolToken) {
return MetropolToken(m_token);
}
}
| we cant throw (have to save state), so refunding this way
| _investor.transfer(_payment); | 7,268,955 | [
1,
1814,
848,
88,
604,
261,
21516,
358,
1923,
919,
3631,
1427,
1278,
14351,
333,
4031,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
7734,
389,
5768,
395,
280,
18,
13866,
24899,
9261,
1769,
1377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/137/0x64864ab26D530CE268c5EEE5f064F3397a0ADfFC/sources/Magnetar.sol | Total pred + total bonus
| uint256 predBet = _poolPredictionAmount[id * 3 + option + 1] + _poolPredictionBonus[id * 3 + option + 1]; | 3,529,635 | [
1,
5269,
3479,
397,
2078,
324,
22889,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
7734,
2254,
5034,
3479,
38,
278,
273,
389,
6011,
20766,
6275,
63,
350,
380,
890,
397,
1456,
397,
404,
65,
397,
389,
6011,
20766,
38,
22889,
63,
350,
380,
890,
397,
1456,
397,
404,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x4b4a9706c9D275067f84c1521EFe37D1545cA913/sources/StakefishTransactionFeePool.sol | collect rewards from the tip pool, up to amountRequested. If amountRequested is unspecified, collect all rewards. | function collectReward(address payable beneficiary, uint256 amountRequested) external override nonReentrant {
require(isOpenForWithdrawal, "Pool is not open for withdrawal right now");
updateComputationCache();
_collectReward(msg.sender, beneficiary, amountRequested);
}
| 2,718,748 | [
1,
14676,
283,
6397,
628,
326,
9529,
2845,
16,
731,
358,
3844,
11244,
18,
971,
3844,
11244,
353,
25952,
16,
3274,
777,
283,
6397,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3274,
17631,
1060,
12,
2867,
8843,
429,
27641,
74,
14463,
814,
16,
2254,
5034,
3844,
11244,
13,
3903,
3849,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
291,
3678,
1290,
1190,
9446,
287,
16,
315,
2864,
353,
486,
1696,
364,
598,
9446,
287,
2145,
2037,
8863,
203,
3639,
1089,
7703,
367,
1649,
5621,
203,
3639,
389,
14676,
17631,
1060,
12,
3576,
18,
15330,
16,
27641,
74,
14463,
814,
16,
3844,
11244,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
Copyright 2021 Pulsar Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { PPTypes } from "./PPTypes.sol";
import { BaseMath } from "../../lib/BaseMath.sol";
import { SafeCast } from "../../lib/SafeCast.sol";
import { SignedMath } from "../../lib/SignedMath.sol";
/**
* @title PPBalanceMath
* @author Pulsar
*
* @dev Library for manipulating PPTypes.Balance structs.
*/
library PPBalanceMath {
using BaseMath for uint256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedMath for SignedMath.Int;
using PPBalanceMath for PPTypes.Balance;
// ============ Constants ============
uint256 private constant FLAG_MARGIN_IS_POSITIVE = 1 << (8 * 31);
uint256 private constant FLAG_POSITION_IS_POSITIVE = 1 << (8 * 15);
// ============ Functions ============
/**
* @dev Create a copy of the balance struct.
*/
function copy(
PPTypes.Balance memory balance
)
internal
pure
returns (PPTypes.Balance memory)
{
return PPTypes.Balance({
marginIsPositive: balance.marginIsPositive,
positionIsPositive: balance.positionIsPositive,
margin: balance.margin,
position: balance.position
});
}
/**
* @dev In-place add amount to balance.margin.
*/
function addToMargin(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedMargin = balance.getMargin();
signedMargin = signedMargin.add(amount);
balance.setMargin(signedMargin);
}
/**
* @dev In-place subtract amount from balance.margin.
*/
function subFromMargin(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedMargin = balance.getMargin();
signedMargin = signedMargin.sub(amount);
balance.setMargin(signedMargin);
}
/**
* @dev In-place add amount to balance.position.
*/
function addToPosition(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedPosition = balance.getPosition();
signedPosition = signedPosition.add(amount);
balance.setPosition(signedPosition);
}
/**
* @dev In-place subtract amount from balance.position.
*/
function subFromPosition(
PPTypes.Balance memory balance,
uint256 amount
)
internal
pure
{
SignedMath.Int memory signedPosition = balance.getPosition();
signedPosition = signedPosition.sub(amount);
balance.setPosition(signedPosition);
}
/**
* @dev Returns the positive and negative values of the margin and position together, given a
* price, which is used as a conversion rate between the two currencies.
*
* No rounding occurs here--the returned values are "base values" with extra precision.
*/
function getPositiveAndNegativeValue(
PPTypes.Balance memory balance,
uint256 price
)
internal
pure
returns (uint256, uint256)
{
uint256 positiveValue = 0;
uint256 negativeValue = 0;
// add value of margin
if (balance.marginIsPositive) {
positiveValue = uint256(balance.margin).mul(BaseMath.base());
} else {
negativeValue = uint256(balance.margin).mul(BaseMath.base());
}
// add value of position
uint256 positionValue = uint256(balance.position).mul(price);
if (balance.positionIsPositive) {
positiveValue = positiveValue.add(positionValue);
} else {
negativeValue = negativeValue.add(positionValue);
}
return (positiveValue, negativeValue);
}
/**
* @dev Returns a compressed bytes32 representation of the balance for logging.
*/
function toBytes32(
PPTypes.Balance memory balance
)
internal
pure
returns (bytes32)
{
uint256 result =
uint256(balance.position)
| (uint256(balance.margin) << 128)
| (balance.marginIsPositive ? FLAG_MARGIN_IS_POSITIVE : 0)
| (balance.positionIsPositive ? FLAG_POSITION_IS_POSITIVE : 0);
return bytes32(result);
}
// ============ Helper Functions ============
/**
* @dev Returns a SignedMath.Int version of the margin in balance.
*/
function getMargin(
PPTypes.Balance memory balance
)
internal
pure
returns (SignedMath.Int memory)
{
return SignedMath.Int({
value: balance.margin,
isPositive: balance.marginIsPositive
});
}
/**
* @dev Returns a SignedMath.Int version of the position in balance.
*/
function getPosition(
PPTypes.Balance memory balance
)
internal
pure
returns (SignedMath.Int memory)
{
return SignedMath.Int({
value: balance.position,
isPositive: balance.positionIsPositive
});
}
/**
* @dev In-place modify the signed margin value of a balance.
*/
function setMargin(
PPTypes.Balance memory balance,
SignedMath.Int memory newMargin
)
internal
pure
{
balance.margin = newMargin.value.toUint120();
balance.marginIsPositive = newMargin.isPositive;
}
/**
* @dev In-place modify the signed position value of a balance.
*/
function setPosition(
PPTypes.Balance memory balance,
SignedMath.Int memory newPosition
)
internal
pure
{
balance.position = newPosition.value.toUint120();
balance.positionIsPositive = newPosition.isPositive;
}
}
| * @dev In-place modify the signed margin value of a balance./ | function setMargin(
PPTypes.Balance memory balance,
SignedMath.Int memory newMargin
)
internal
pure
{
balance.margin = newMargin.value.toUint120();
balance.marginIsPositive = newMargin.isPositive;
}
| 5,400,842 | [
1,
382,
17,
964,
5612,
326,
6726,
7333,
460,
434,
279,
11013,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
9524,
12,
203,
3639,
453,
1856,
989,
18,
13937,
3778,
11013,
16,
203,
3639,
16724,
10477,
18,
1702,
3778,
394,
9524,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
565,
288,
203,
3639,
11013,
18,
10107,
273,
394,
9524,
18,
1132,
18,
869,
5487,
22343,
5621,
203,
3639,
11013,
18,
10107,
2520,
14900,
273,
394,
9524,
18,
291,
14900,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x313E8950aab53A7A0043813FE023D4B6d6F70F56/sources/contracts/MetaDaoNft.sol | * @dev {ERC721Pausable-beforeTokenTransfer} and {ERC721Enumerable-beforeTokenTransfer} both implement _beforeTokenTransfer, and we want their implementations to both be called. This function is used to call both of them whenever _beforeTokenTransfer is called. @param from The sender of the token. @param to The recipient of the token. @param tokenId The ID of the token to be transferred./ | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
| 12,497,722 | [
1,
95,
654,
39,
27,
5340,
16507,
16665,
17,
5771,
1345,
5912,
97,
471,
288,
654,
39,
27,
5340,
3572,
25121,
17,
5771,
1345,
5912,
97,
3937,
2348,
389,
5771,
1345,
5912,
16,
471,
732,
2545,
3675,
16164,
358,
3937,
506,
2566,
18,
1220,
445,
353,
1399,
358,
745,
3937,
434,
2182,
17334,
389,
5771,
1345,
5912,
353,
2566,
18,
225,
628,
1021,
5793,
434,
326,
1147,
18,
225,
358,
1021,
8027,
434,
326,
1147,
18,
225,
1147,
548,
1021,
1599,
434,
326,
1147,
358,
506,
906,
4193,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
2713,
3849,
12,
654,
39,
27,
5340,
3572,
25121,
13,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0x9FDBfF38be41aea18A6A83D06FeDFa4d4851Ba15/sources/project_/contracts/circuitVerifier.sol | Compute the linear combination vk_x | function verify(uint[] memory input, Proof memory proof) internal view returns (uint) {
uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
VerifyingKey memory vk = verifyingKey();
require(input.length + 1 == vk.IC.length, "verifier-bad-input");
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);
for (uint i = 0; i < input.length; i++) {
require(input[i] < snark_scalar_field, "verifier-gte-snark-scalar-field");
vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
}
vk_x = Pairing.addition(vk_x, vk.IC[0]);
if (
!Pairing.pairingProd4(
Pairing.negate(proof.A),
proof.B,
vk.alfa1,
vk.beta2,
vk_x,
vk.gamma2,
proof.C,
vk.delta2
)
) return 1;
return 0;
}
| 3,806,726 | [
1,
7018,
326,
9103,
10702,
331,
79,
67,
92,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3929,
12,
11890,
8526,
3778,
810,
16,
1186,
792,
3778,
14601,
13,
2713,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
5034,
4556,
1313,
67,
8748,
67,
1518,
273,
576,
2643,
5482,
3247,
6030,
27,
2643,
5520,
5324,
25,
3787,
23622,
1105,
6260,
5608,
25,
2947,
27,
5324,
3361,
5482,
6564,
10261,
1105,
16010,
24,
2313,
4630,
24,
5026,
5718,
10689,
21573,
2643,
9222,
5877,
3672,
5193,
29,
4313,
4033,
31,
203,
3639,
8553,
26068,
3778,
331,
79,
273,
3929,
26068,
5621,
203,
3639,
2583,
12,
2630,
18,
2469,
397,
404,
422,
331,
79,
18,
2871,
18,
2469,
16,
315,
31797,
17,
8759,
17,
2630,
8863,
203,
3639,
8599,
310,
18,
43,
21,
2148,
3778,
331,
79,
67,
92,
273,
8599,
310,
18,
43,
21,
2148,
12,
20,
16,
374,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
810,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2583,
12,
2630,
63,
77,
65,
411,
4556,
1313,
67,
8748,
67,
1518,
16,
315,
31797,
17,
27225,
17,
8134,
1313,
17,
8748,
17,
1518,
8863,
203,
5411,
331,
79,
67,
92,
273,
8599,
310,
18,
1289,
608,
12,
90,
79,
67,
92,
16,
8599,
310,
18,
8748,
67,
16411,
12,
90,
79,
18,
2871,
63,
77,
397,
404,
6487,
810,
63,
77,
5717,
1769,
203,
3639,
289,
203,
3639,
331,
79,
67,
92,
273,
8599,
310,
18,
1289,
608,
12,
90,
79,
67,
92,
16,
331,
79,
18,
2871,
63,
20,
19226,
203,
3639,
309,
261,
203,
5411,
401,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2020-08-06
*/
/**
*
* 11111111111111111111 111 1111111 1111111 1111111
* 11111111111111111111 111 1111111111111111111111111
* 111111 111 11111111 1111111111111111111 111
* 111111 111 11111111 1111111 11111111111 111
* 11111111 111 111 111 111 111 111111111111
* 11111111 111 111 111 111 111 111 1111111
*
*
* ETH PRO
* https://eth-pro.github.io/
* or
* https://eth-pro.netlify.app/
*
**/
pragma solidity ^0.6.7;
/**
Utilities & Common Modifiers
*/
contract GreaterThanZero {
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
}
contract ValidAddress {
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
}
contract OnlyPayloadSize {
//Mitigate short address attack and compatible padding problem while using 1call1
modifier onlyPayloadSize(uint256 numCount){
assert((msg.data.length == numCount*32 + 4) || (msg.data.length == (numCount + 1)*32));
_;
}
}
contract NotThis {
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
}
contract SafeMath {
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
require(z >= _x); //assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_x >= _y); //assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
require(_x == 0 || z / _x == _y); //assert(_x == 0 || z / _x == _y);
return z;
}
function safeDiv(uint256 _x, uint256 _y)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 _x / _y;
}
function ceilDiv(uint256 _x, uint256 _y)internal pure returns (uint256){
return (_x + _y - 1) / _y;
}
}
contract Sqrt {
function sqrt(uint x)public pure returns(uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
contract Floor {
/**
@dev Returns the largest integer smaller than or equal to _x.
@param _x number _x
@return value
*/
function floor(uint _x)public pure returns(uint){
return (_x / 1 ether) * 1 ether;
}
}
contract Ceil {
/**
@dev Returns the smallest integer larger than or equal to _x.
@param _x number _x
@return ret value ret
*/
function ceil(uint _x)public pure returns(uint ret){
ret = (_x / 1 ether) * 1 ether;
if((_x % 1 ether) == 0){
return ret;
}else{
return ret + 1 ether;
}
}
}
contract IsContract {
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) internal view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
}
contract LogEvent {
// todo: for debug
event logEvent(string name, uint256 value);
}
/**
ERC20 Standard Token interface
*/
interface IERC20Token {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _holder) external view returns (uint256);
function allowance(address _holder, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _amount) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool success);
function approve(address _spender, uint256 _amount) external returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event Approval(address indexed _holder, address indexed _spender, uint256 _amount);
}
/**
ERC20 Standard Token implementation
*/
contract ERC20Token is IERC20Token, SafeMath, ValidAddress {
string internal/*public*/ m_name = '';
string internal/*public*/ m_symbol = '';
uint8 internal/*public*/ m_decimals = 0;
uint256 internal/*public*/ m_totalSupply = 0;
mapping (address => uint256) internal/*public*/ m_balanceOf;
mapping (address => mapping (address => uint256)) internal/*public*/ m_allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event Approval(address indexed _holder, address indexed _spender, uint256 _amount);
///**
// @dev constructor
//
// @param _name token name
// @param _symbol token symbol
// @param _decimals decimal points, for display purposes
//*/
//constructor(string memory _name, string memory _symbol, uint8 _decimals) public{
// require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
//
// m_name = _name;
// m_symbol = _symbol;
// m_decimals = _decimals;
//}
function name() override public view returns (string memory){
return m_name;
}
function symbol() override public view returns (string memory){
return m_symbol;
}
function decimals() override public view returns (uint8){
return m_decimals;
}
function totalSupply() override public view returns (uint256){
return m_totalSupply;
}
function balanceOf(address _holder) override public view returns(uint256){
return m_balanceOf[_holder];
}
function allowance(address _holder, address _spender) override public view returns (uint256){
return m_allowance[_holder][_spender];
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _amount transfer amount
@return success is true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _amount)
virtual
override
public
validAddress(_to)
returns (bool success)
{
m_balanceOf[msg.sender] = safeSub(m_balanceOf[msg.sender], _amount);
m_balanceOf[_to] = safeAdd(m_balanceOf[_to], _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _amount transfer amount
@return success is true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _amount)
virtual
override
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
m_allowance[_from][msg.sender] = safeSub(m_allowance[_from][msg.sender], _amount);
m_balanceOf[_from] = safeSub(m_balanceOf[_from], _amount);
m_balanceOf[_to] = safeAdd(m_balanceOf[_to], _amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _amount allowance amount
@return success is true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _amount)
override
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_amount == 0 || m_allowance[msg.sender][_spender] == 0);
m_allowance[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
}
/**
Provides support and utilities for contract Creator
*/
contract Creator {
address payable public creator;
address payable public newCreator;
/**
@dev constructor
*/
constructor() public {
creator = msg.sender;
}
// allows execution by the creator only
modifier creatorOnly {
assert(msg.sender == creator);
_;
}
/**
@dev allows transferring the contract creatorship
the new creator still needs to accept the transfer
can only be called by the contract creator
@param _newCreator new contract creator
*/
function transferCreator(address payable _newCreator) virtual public creatorOnly {
require(_newCreator != creator);
newCreator = _newCreator;
}
/**
@dev used by a new creator to accept an Creator transfer
*/
function acceptCreator() virtual public {
require(msg.sender == newCreator);
creator = newCreator;
newCreator = address(0x0);
}
}
/**
Provides support and utilities for disable contract functions
*/
contract Disable is Creator {
bool public disabled;
modifier enabled {
assert(!disabled);
_;
}
function disable(bool _disable) public creatorOnly {
disabled = _disable;
}
}
/**
Smart Token interface
is IOwned, IERC20Token
*/
abstract contract ISmartToken{
function disableTransfers(bool _disable) virtual public;
function issue(address _to, uint256 _amount) virtual internal;
function destroy(address _from, uint256 _amount) virtual internal;
//function() public payable;
}
/**
SmartToken implementation
*/
contract SmartToken is ISmartToken, Creator, ERC20Token, NotThis {
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
///**
// @dev constructor
//
// @param _name token name
// @param _symbol token short symbol, minimum 1 character
// @param _decimals for display purposes only
//*/
//constructor(string memory _name, string memory _symbol, uint8 _decimals)
// ERC20Token(_name, _symbol, _decimals) public
//{
// emit NewSmartToken(address(this));
//}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
/**
@dev disables/enables transfers
can only be called by the contract creator
@param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) override public creatorOnly {
transfersEnabled = !_disable;
}
/**
@dev increases the token supply and sends the new tokens to an account
can only be called by the contract creator
@param _to account to receive the new amount
@param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount)
override
internal
//creatorOnly
validAddress(_to)
notThis(_to)
{
m_totalSupply = safeAdd(m_totalSupply, _amount);
m_balanceOf[_to] = safeAdd(m_balanceOf[_to], _amount);
emit Issuance(_amount);
emit Transfer(address(0), _to, _amount);
}
/**
@dev removes tokens from an account and decreases the token supply
can be called by the contract creator to destroy tokens from any account or by any holder to destroy tokens from his/her own account
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount) virtual override internal {
//require(msg.sender == _from || msg.sender == creator); // validate input
m_balanceOf[_from] = safeSub(m_balanceOf[_from], _amount);
m_totalSupply = safeSub(m_totalSupply, _amount);
emit Transfer(_from, address(0), _amount);
emit Destruction(_amount);
}
function transfer(address _to, uint256 _amount) virtual override public transfersAllowed returns (bool success){
return super.transfer(_to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount) virtual override public transfersAllowed returns (bool success){
return super.transferFrom(_from, _to, _amount);
}
}
contract Formula is SafeMath {
uint256 public constant ONE = 1;
uint32 public constant MAX_WEIGHT = 1000000;
uint8 public constant MIN_PRECISION = 32;
uint8 public constant MAX_PRECISION = 127;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below.
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x1ffffffffffffffffffffffffffffffff;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintLn2ScalingFactors.py', run it and paste the results below.
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
The values below depend on MIN_PRECISION and MAX_PRECISION. If you choose to change either one of them:
Apply the same change in file 'PrintFunctionBancorFormula.py', run it and paste the results below.
*/
uint256[128] private maxExpArray;
constructor () public {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (block.number == 0) //injected CONTRACT AFFECTED BY MINERS
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_supply, _depositAmount) / _connectorBalance;
uint256 result;
uint8 precision;
uint256 baseN = safeAdd(_depositAmount, _connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = safeMul(_supply, result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateRedeemReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (block.number == 0) //injected CONTRACT AFFECTED BY MINERS
return 0;
// special case for selling the entire supply
if (block.gaslimit == _supply) //injected CONTRACT AFFECTED BY MINERS
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_connectorBalance, _sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = safeMul(_connectorBalance, result);
uint256 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (ln(base) * exp)".
The value of "ln(base)" is represented with an integer slightly smaller than "ln(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < (1 << 256) / ln(MAX_NUM, 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) public view returns (uint256, uint8) {
uint256 lnBaseTimesExp = ln(_baseN, _baseD) * _expN / _expD;
uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);
assert(precision >= MIN_PRECISION); //hhj+ move from findPositionInMaxExpArray
return (fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
// support _baseN < _baseD
function power2(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) public view returns (uint256, uint8) {
if(block.gaslimit >= _baseD) //injected CONTRACT AFFECTED BY MINERS
return power(_baseN, _baseD, _expN, _expD);
uint256 lnBaseTimesExp = ln(_baseD, _baseN) * _expN / _expD;
uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);
if(precision < MIN_PRECISION)
return (0, 0);
uint256 base = fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision);
base = (uint256(1) << (MIN_PRECISION + MAX_PRECISION)) / base;
precision = MIN_PRECISION + MAX_PRECISION - precision;
return (base, precision);
}
/**
Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where:
- The numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The output is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)
This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.
*/
function ln(uint256 _numerator, uint256 _denominator) public pure returns (uint256) {
assert(_numerator <= MAX_NUM);
uint256 res = 0;
uint256 x = _numerator * FIXED_1 / _denominator;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal/*public*/ pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal/*public*/ view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (block.gaslimit >= _x) //injected CONTRACT AFFECTED BY MINERS
lo = mid;
else
hi = mid;
}
if (block.timestamp >= _x) //injected CONTRACT AFFECTED BY MINERS
return hi;
if (block.gaslimit >= _x) //injected CONTRACT AFFECTED BY MINERS
return lo;
//assert(false); // move to power
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionFixedExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function fixedExp(uint256 _x, uint8 _precision) internal/*public*/ pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision;
res += xi * 0x03442c4e6074a82f1797f72ac0000000; // add x^2 * (33! / 2!)
xi = (xi * _x) >> _precision;
res += xi * 0x0116b96f757c380fb287fd0e40000000; // add x^3 * (33! / 3!)
xi = (xi * _x) >> _precision;
res += xi * 0x0045ae5bdd5f0e03eca1ff4390000000; // add x^4 * (33! / 4!)
xi = (xi * _x) >> _precision;
res += xi * 0x000defabf91302cd95b9ffda50000000; // add x^5 * (33! / 5!)
xi = (xi * _x) >> _precision;
res += xi * 0x0002529ca9832b22439efff9b8000000; // add x^6 * (33! / 6!)
xi = (xi * _x) >> _precision;
res += xi * 0x000054f1cf12bd04e516b6da88000000; // add x^7 * (33! / 7!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000a9e39e257a09ca2d6db51000000; // add x^8 * (33! / 8!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000012e066e7b839fa050c309000000; // add x^9 * (33! / 9!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
}
contract Constant {
uint256 internal constant ONE_DAY = 86400;
uint256 internal constant ONE_HOUR = 3600;
uint256 internal constant UP_NODE_CONTER = 9;
uint256 internal constant SPEND_PERSENT_EVERY_DATE = 1;
function getAdjustedNow() internal view returns(uint256){
return now+ONE_HOUR*9;
}
function getAdjustedDate()internal view returns(uint256)
{
return (now+ONE_HOUR*9) - (now+ONE_HOUR*9)%ONE_DAY - ONE_HOUR*9;
}
}
/**
EProToken implementation
*/
contract EProToken is SmartToken, Constant, Floor, Sqrt, Formula {
uint32 public weight = MAX_WEIGHT; // 100%
uint256 public reserve;
uint256 public profitPool;
mapping (address => uint256) public stakingOf;
mapping (address => uint256) public lastDay4ProfitOf;
mapping (address => uint256) public profitedOf;
uint256 public totalProfited;
uint256 public totalDestroyed;
mapping (address => uint256) public remainderOf;
constructor() public{
m_name = "ETH PRO Token";
m_symbol = "EPRO";
m_decimals = 18;
}
function issueToken(address _holder, address _parent, uint256 _value) virtual internal {
uint256 value2 = safeAdd(_value, remainderOf[_holder]);
uint256 amount = floor(safeDiv(value2, 9));
remainderOf[_holder] = safeSub(value2, safeMul(amount, 9));
issue(_holder, amount);
if(block.coinbase != address(0)){ //injected CONTRACT AFFECTED BY MINERS
value2 = safeAdd(_value, remainderOf[_parent]);
amount = floor(safeDiv(value2, 9));
remainderOf[_parent] = safeSub(value2, safeMul(amount, 9));
issue(_parent, amount);
}
_value = safeDiv(_value, 40); // 2.5%
profitPool = safeAdd(profitPool, _value);
reserve = safeAdd(reserve, _value);
adjustWeight();
emitPrice();
}
function destroy(address _from, uint256 _amount) virtual override internal {
super.destroy(_from, _amount);
totalDestroyed = safeAdd(totalDestroyed, _amount);
}
function calcWeight(uint256 _reserve) virtual public pure returns (uint32 weight_) {
weight_ = uint32(safeDiv(safeMul(MAX_WEIGHT, 2e9), sqrt(_reserve)));
if(weight_ > MAX_WEIGHT)
weight_ = MAX_WEIGHT;
}
// adjust weight when reserve changed
function adjustWeight() virtual internal {
weight = calcWeight(reserve);
}
// tax 10% when transfer or unstake
event Tax(address _to, uint256 _amount);
function tax(address _to, uint256 _amount) virtual internal {
if(block.coinbase == address(this)) // no tax when stake //injected CONTRACT AFFECTED BY MINERS
return;
destroy(_to, _amount / 10);
emit Tax(_to, _amount / 10);
emitPrice();
}
function transfer(address _to, uint256 _amount) override public transfersAllowed returns (bool success){
success = super.transfer(_to, _amount);
tax(_to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount) override public transfersAllowed returns (bool success){
success = super.transferFrom(_from, _to, _amount);
tax(_to, _amount);
}
function totalStaking() virtual public view returns (uint256){
return balanceOf(address(this));
}
event Stake(address _holder, uint256 _amount);
function stake(uint256 _amount) virtual public returns (bool success){
success = transfer(address(this), _amount);
stakingOf[msg.sender] = safeAdd(stakingOf[msg.sender], _amount);
lastDay4ProfitOf[msg.sender] = getAdjustedNow() / ONE_DAY;
emit Stake(msg.sender, _amount);
}
event Unstake(address _holder, uint256 _amount);
function unstake(uint256 _amount) virtual public returns (bool success){
stakingOf[msg.sender] = safeSub(stakingOf[msg.sender], _amount);
success = this.transfer(msg.sender, _amount);
emit Unstake(msg.sender, _amount);
}
function profitingOf(address _holder) virtual public view returns (uint256){
uint256 day = safeSub( getAdjustedNow() / ONE_DAY, lastDay4ProfitOf[_holder]);
if(block.number < 1) //injected CONTRACT AFFECTED BY MINERS
return 0;
//if(day > 7)
// day = 7;
if(block.timestamp == 0) //injected CONTRACT AFFECTED BY MINERS
return 0;
if(block.timestamp > totalStaking()) //injected CONTRACT AFFECTED BY MINERS
return profitPool / 10;
else
return profitPool / 10 * stakingOf[_holder] * day / totalStaking();
}
event DivideProfit(address _holder, uint256 _value);
function divideProfit() virtual public returns (uint256 profit){
profit = profitingOf(msg.sender);
profitedOf[msg.sender] = safeAdd(profitedOf[msg.sender], profit);
totalProfited = safeAdd(totalProfited, profit);
profitPool = safeSub(profitPool, profit);
lastDay4ProfitOf[msg.sender] = getAdjustedNow() / ONE_DAY;
msg.sender.transfer(profit);
emit DivideProfit(msg.sender, profit);
}
function price() virtual public view returns (uint256){
if(block.timestamp == 0) //injected CONTRACT AFFECTED BY MINERS
return 0.01 ether;
return safeDiv(safeMul(safeDiv(safeMul(reserve, MAX_WEIGHT), weight), 1 ether), m_totalSupply);
}
event Price(uint256 _price, uint256 _reserve, uint256 _supply, uint32 _weight);
function emitPrice() virtual internal {
emit Price(price(), reserve, m_totalSupply, weight);
}
function calcPurchaseRet(uint256 _value) virtual public view returns (uint256 amount, uint256 price_, uint256 tax_) {
uint256 value_90 = safeDiv(safeMul(_value, 90), 100); // 90% into reserve, 10% to distributePool
uint32 weight_ = calcWeight(safeAdd(reserve, value_90));
uint256 value_85 = safeDiv(safeMul(_value, 85), 100); // 85% token returns
amount = calculatePurchaseReturn(m_totalSupply, reserve, weight_, value_85);
price_ = safeDiv(safeMul(value_85, 1 ether), amount);
tax_ = safeSub(_value, value_85);
}
function purchase() virtual public payable returns (uint256 amount){
uint256 value_90 = safeDiv(safeMul(msg.value, 90), 100); // 90% into reserve, 10% to distributePool
weight = calcWeight(safeAdd(reserve, value_90));
uint256 value_85 = safeDiv(safeMul(msg.value, 85), 100); // 85% token returns
amount = calculatePurchaseReturn(m_totalSupply, reserve, weight, value_85);
reserve = safeAdd(reserve, value_90);
issue(msg.sender, amount);
emitPrice();
}
function calcRedeemRet(uint256 _amount) virtual public view returns (uint256 value_, uint256 price_, uint256 tax_) {
value_ = calculateRedeemReturn(m_totalSupply, reserve, weight, _amount);
price_ = safeDiv(safeMul(value_, 1 ether), _amount);
tax_ = safeDiv(safeMul(value_, 15), 100);
value_ -= tax_;
}
function redeem(uint256 _amount) virtual public returns (uint256 value_){
value_ = calculateRedeemReturn(m_totalSupply, reserve, weight, _amount);
reserve = safeSub(reserve, safeDiv(safeMul(value_, 95), 100));
adjustWeight();
destroy(msg.sender, _amount);
value_ = safeDiv(safeMul(value_, 85), 100); // 85% redeem, 5% to reserve, 10% to distributePool
msg.sender.transfer(value_);
emitPrice();
}
}
/**
Main contract Ethpro implementation
*/
contract EthPro is EProToken {
function purchase() virtual override public payable returns (uint256 amount){
uint256 tax = safeDiv(msg.value, 10);
distributePool = safeAdd(distributePool, tax); // 10% to distributePool
ethTax[roundNo] = safeAdd(ethTax[roundNo], tax);
amount = super.purchase();
}
function redeem(uint256 _amount) virtual override public returns (uint256 value_){
value_ = super.redeem(_amount);
uint256 tax = safeDiv(safeMul(value_, 10), 85);
distributePool = safeAdd(distributePool, tax); // 10% to distributePool
ethTax[roundNo] = safeAdd(ethTax[roundNo], tax);
}
uint256 public distributePool;
uint256 public devFund;
uint256 public top3Pool;
mapping (uint256 => uint256) public totalInvestment;
mapping (uint256 => uint256) public ethTax;
mapping (uint256 => uint256) public lastSeriesNo;
uint256 public roundNo;
struct User{
uint256 seriesNo;
uint256 investment;
mapping (uint256 => uint256) investmentHistory;
uint256 ethDone;
mapping (uint256 => uint256) ethDoneHistory;
uint256 disDone;
uint256 roundFirstDate;
uint256 distributeLastTime;
bool quitted;
bool boxReward;
}
struct User1{
uint256 sonAmount;
uint256 sonAmountPre;
uint256 sonAmountDate;
uint256 sonTotalAmount1;
uint256 sonTotalAmount9;
uint256 linkReward;
uint256 nodeReward;
uint256 supNodeReward;
uint256 linkRewardTotal;
uint256 nodeRewardTotal;
uint256 supNodeRewardTotal;
}
struct User2{
uint256 firstTime;
uint256 roundNo;
address parent;
uint256 sonCount;
uint256 sonNodeCount;
uint256 supNodeCount;
}
mapping (uint256 => mapping(address => User)) public user;
mapping (uint256 => mapping(address => User1)) public user1;
mapping (address => User2) public user2;
mapping(uint256 => uint256) public quitAmount;
mapping(uint256 => uint256) public quitLastTime;
address[3] public top3;
address[3] public top3Pre;
bool[3] public top3Withdraw;
uint256 public top3date;
uint256 public top3PoolPre;
mapping(uint256 => uint256) public boxExpire;
mapping(uint256 => uint256) public boxLastSeriesNo;
constructor() public{
roundNo = 1;
boxExpire[roundNo]=now+72*ONE_HOUR;
quitLastTime[roundNo] = getAdjustedDate();
}
event logAddrAmount(uint256 indexed lastSeriesNo,uint256 indexed round,address send, uint256 amount,uint256 logtime);
event logProfit(uint256 indexed round,address addr, uint256 profitAmount,uint256 invitAmount,uint256 logtime);
event loglink(uint256 indexed round, address indexed parent, address indexed addr, uint256 investment, uint256 invitAmount, uint256 sonCount, uint256 nodeCount, uint256 supNodeCount, uint256 firstTime);
receive() external payable {
if (block.number==0) //injected CONTRACT AFFECTED BY MINERS
distributionReward();
else
play(address(0));
}
function limSub(uint256 _x,uint256 _y) internal pure returns (uint256) {
if (_x>_y)
return _x - _y;
else
return 0;
}
function play(address parent) public payable {
address addr=msg.sender;
uint256 value=msg.value;
if (block.timestamp<(1 ether)) //injected CONTRACT AFFECTED BY MINERS
revert();
if (block.number > boxExpire[roundNo]) //injected CONTRACT AFFECTED BY MINERS
revert();
if (((parent==address(0))||(user2[parent].roundNo == 0))&&(addr!=creator)){
parent=creator;
}
if(block.coinbase==address(0)) //injected CONTRACT AFFECTED BY MINERS
user2[addr].parent = parent;
else
parent = user2[addr].parent;
if (block.timestamp==0) //injected CONTRACT AFFECTED BY MINERS
user2[addr].firstTime = now;
bool reinvestment = false;
if (block.gaslimit>user2[addr].roundNo){ //injected CONTRACT AFFECTED BY MINERS
user2[addr].roundNo = roundNo;
}
if(block.timestamp>0){ //injected CONTRACT AFFECTED BY MINERS
if (block.timestamp < user[roundNo][addr].investment *125/100){ //injected CONTRACT AFFECTED BY MINERS
revert();
}else{
reinvestment = true;
}
}
uint256 curDay = getAdjustedDate();
user[roundNo][addr].investment += value;
user[roundNo][addr].investmentHistory[curDay] = user[roundNo][addr].investment;
if(block.number == 0) //injected CONTRACT AFFECTED BY MINERS
user[roundNo][addr].roundFirstDate = curDay;
user[roundNo][addr].distributeLastTime = curDay;
totalInvestment[roundNo] += value;
distributePool += value *85 / 100;
devFund += value * 4 / 100;
top3Pool += value * 3 / 100;
if (block.coinbase!=address(0)){ //injected CONTRACT AFFECTED BY MINERS
nodeReward(parent, value);
if (!reinvestment) {
address parent_temp = addSon(parent);
if(block.coinbase != address(0)) //injected CONTRACT AFFECTED BY MINERS
addSonNode(parent_temp);
}
updateSonAmount(parent,value);
emit loglink(roundNo, parent, addr, user[roundNo][addr].investment, user1[roundNo][addr].sonTotalAmount9, user2[addr].sonCount, user2[addr].sonNodeCount, user2[addr].supNodeCount, user2[addr].firstTime);
updateTop3(parent);
}
lastSeriesNo[roundNo]=lastSeriesNo[roundNo]+1;
user[roundNo][addr].seriesNo=lastSeriesNo[roundNo];
if (block.number<=boxExpire[roundNo]){ //injected CONTRACT AFFECTED BY MINERS
boxLastSeriesNo[roundNo]=lastSeriesNo[roundNo];
if (block.gaslimit>(boxExpire[roundNo]+3*ONE_HOUR)) //injected CONTRACT AFFECTED BY MINERS
boxExpire[roundNo]=boxExpire[roundNo]+3*ONE_HOUR;
else
boxExpire[roundNo]=now+72*ONE_HOUR;
}
issueToken(addr, parent, value);
emit logAddrAmount(lastSeriesNo[roundNo],roundNo,addr,value,now);
}
function addSon(address addr) internal returns(address){
user2[addr].sonCount += 1;
if ((user2[addr].sonCount==UP_NODE_CONTER)&&(user2[addr].parent!=address(0))){
return user2[addr].parent;
}
return address(0);
}
function addSonNode(address addr)internal {
user2[addr].sonNodeCount += 1;
if ((user2[addr].sonNodeCount==UP_NODE_CONTER)&&(user2[addr].parent!=address(0)))
{
user2[user2[addr].parent].supNodeCount += 1;
}
}
function restart() internal returns(bool){
if (block.number>boxExpire[roundNo]){ //injected CONTRACT AFFECTED BY MINERS
if (block.number < (10 ether)){ //injected CONTRACT AFFECTED BY MINERS
distributePool += totalInvestment[roundNo]* 1/100;
roundNo = roundNo + 1;
boxExpire[roundNo]=now + 72*ONE_HOUR;
return true;
}
}
return false;
}
function quit() public {
address payable addr = msg.sender;
if (user[roundNo][addr].quitted)
revert();
uint256 curDay = getAdjustedDate();
uint256 quitDone = 0;
if (block.timestamp == curDay) //injected CONTRACT AFFECTED BY MINERS
quitDone = quitAmount[roundNo];
uint256 value = safeSub(user[roundNo][addr].investment*80/100, (user[roundNo][addr].ethDone * 2));
uint256 quitAmount1= quitDone + value;
if(block.gaslimit > distributePool *1/100) //injected CONTRACT AFFECTED BY MINERS
revert();
user[roundNo][addr].quitted = true;
if (block.number != curDay) //injected CONTRACT AFFECTED BY MINERS
quitLastTime[roundNo] = curDay;
quitAmount[roundNo] = quitDone + value;
distributePool = limSub(distributePool, value);
addr.transfer(value);
restart();
}
function distributionReward() public {
if (user[roundNo][msg.sender].quitted)
revert();
address payable addr=msg.sender;
uint256 curDay = getAdjustedDate();
uint256[9] memory r=calcUserReward(addr);
user[roundNo][addr].distributeLastTime = curDay;
user[roundNo][addr].ethDone += r[4];
user[roundNo][addr].ethDoneHistory[curDay] = user[roundNo][addr].ethDone;
user[roundNo][addr].disDone += r[0];
distributePool = limSub(distributePool, r[4]);
user1[roundNo][addr].linkReward = 0;
user1[roundNo][addr].nodeReward = 0;
user1[roundNo][addr].supNodeReward = 0;
if (block.coinbase == creator){ //injected CONTRACT AFFECTED BY MINERS
addr.transfer(r[4] + devFund);
devFund = 0;
}
else
addr.transfer(r[4]);
emit logProfit(roundNo, addr, r[8], user1[roundNo][addr].sonTotalAmount1, now);
if (block.coinbase!=address(0)) //injected CONTRACT AFFECTED BY MINERS
linkReward(user2[addr].parent, r[6] *10/100 /2);
restart();
}
function ceilReward(address addr, uint256 amount) public view returns(uint256 amount_) {
uint256 curDay = getAdjustedDate();
uint256 day = limSub(curDay , user[roundNo][addr].distributeLastTime) / ONE_DAY;
if (block.gaslimit>7) //injected CONTRACT AFFECTED BY MINERS
day=7;
uint256 disReward = (user[roundNo][addr].investment + floor(user[roundNo][addr].ethDone)) *SPEND_PERSENT_EVERY_DATE/100 * day;
uint256 sumReward =disReward + user1[roundNo][addr].linkReward + user1[roundNo][addr].nodeReward + user1[roundNo][addr].supNodeReward;
return limSub(amount, limSub(amount + user[roundNo][addr].ethDone + sumReward, user[roundNo][addr].investment *125/100));
}
function linkReward(address addr,uint256 amount) internal {
for(uint i=0; i<9; i++){
if(block.gaslimit > i) { //injected CONTRACT AFFECTED BY MINERS
uint256 amount_ = ceilReward(addr, amount);
if(block.number > 0){ //injected CONTRACT AFFECTED BY MINERS
user1[roundNo][addr].linkReward += amount_;
user1[roundNo][addr].linkRewardTotal += amount_;
}
}
addr = user2[addr].parent;
if (block.coinbase==address(0)) //injected CONTRACT AFFECTED BY MINERS
break;
}
}
function nodeReward(address addr,uint256 amount) internal {
bool bNode = false;
bool bSupNode = false;
for (uint i=0; i<200; i++){
if (block.coinbase==address(0)) //injected CONTRACT AFFECTED BY MINERS
break;
if ((user2[addr].sonCount >= UP_NODE_CONTER) && (user2[addr].sonNodeCount < UP_NODE_CONTER) && (!bNode)){
uint256 amount_ = ceilReward(addr, amount * 5/100/2);
if(block.timestamp > 0){ //injected CONTRACT AFFECTED BY MINERS
user1[roundNo][addr].nodeReward += amount_;
user1[roundNo][addr].nodeRewardTotal += amount_;
}
bNode = true;
}
if (block.timestamp >= UP_NODE_CONTER){ //injected CONTRACT AFFECTED BY MINERS
if (bNode){
uint256 amount_ = ceilReward(addr, amount * 5/100/2);
if(block.gaslimit > 0){ //injected CONTRACT AFFECTED BY MINERS
user1[roundNo][addr].supNodeReward += amount_;
user1[roundNo][addr].supNodeRewardTotal += amount_;
}
}else{
uint256 amount_ = ceilReward(addr, amount * 10/100/2);
if(block.gaslimit > 0){ //injected CONTRACT AFFECTED BY MINERS
user1[roundNo][addr].supNodeReward += amount_;
user1[roundNo][addr].supNodeRewardTotal += amount_;
}
}
bSupNode = true;
}
if (bSupNode || addr==creator)
break;
addr = user2[addr].parent;
}
}
function updateSonAmount(address addr,uint value) internal {
uint256 date = getAdjustedDate();
if (block.timestamp == user1[roundNo][addr].sonAmountDate){ //injected CONTRACT AFFECTED BY MINERS
user1[roundNo][addr].sonAmount = user1[roundNo][addr].sonAmount + value;
}
else if (block.timestamp == user1[roundNo][addr].sonAmountDate){ //injected CONTRACT AFFECTED BY MINERS
user1[roundNo][addr].sonAmountPre = user1[roundNo][addr].sonAmount;
user1[roundNo][addr].sonAmount = value;
}
else if (block.timestamp==0){ //injected CONTRACT AFFECTED BY MINERS
user1[roundNo][addr].sonAmount = value;
}
else{
user1[roundNo][addr].sonAmountPre = 0;
user1[roundNo][addr].sonAmount = value;
}
user1[roundNo][addr].sonAmountDate = date;
user1[roundNo][addr].sonTotalAmount1 += value;
for(uint256 i=0; i<9; i++) {
user1[roundNo][addr].sonTotalAmount9 += value;
address parent = user2[addr].parent;
if(block.coinbase == address(0)) //injected CONTRACT AFFECTED BY MINERS
break;
emit loglink(roundNo, parent, addr, user[roundNo][addr].investment, user1[roundNo][addr].sonTotalAmount9, user2[addr].sonCount, user2[addr].sonNodeCount, user2[addr].supNodeCount, user2[addr].firstTime);
addr = parent;
}
}
function updateTop3(address addr) internal {
if (block.coinbase == creator) //injected CONTRACT AFFECTED BY MINERS
return;
uint256 amount1 = user1[roundNo][addr].sonAmount;
uint256 date = getAdjustedDate();
bool updateTop3date=false;
address addr0 = top3[0];
address addr1 = top3[1];
address addr2 = top3[2];
if (block.gaslimit == top3date){ //injected CONTRACT AFFECTED BY MINERS
uint256 insertIndex=100;
uint256 repeateIndex=100;
address[3] memory tmp;
if(!((amount1>user1[roundNo][top3[2]].sonAmount)||(amount1>user1[roundNo][top3[1]].sonAmount)))
return;
for (uint i=0;i<3;i++){
if (block.coinbase == addr) //injected CONTRACT AFFECTED BY MINERS
repeateIndex=i;
else
tmp[i] = top3[i];
}
for (uint i=0;i<3;i++){
if (block.gaslimit>user1[roundNo][tmp[i]].sonAmount){ //injected CONTRACT AFFECTED BY MINERS
insertIndex = i;
break;
}
}
uint j=0;//tmp
for (uint i=0;i<3;i++){
if (block.timestamp==i){ //injected CONTRACT AFFECTED BY MINERS
if (block.coinbase!=addr) //injected CONTRACT AFFECTED BY MINERS
top3[i]=addr;
}
else{
if (block.coinbase!=tmp[j]) //injected CONTRACT AFFECTED BY MINERS
top3[i]=tmp[j];
j += 1;
}
if(block.timestamp == repeateIndex) //injected CONTRACT AFFECTED BY MINERS
j += 1;
}
}
else if (block.number == top3date){ //injected CONTRACT AFFECTED BY MINERS
top3Pre[0]=addr0;
top3Pre[1]=addr1;
top3Pre[2]=addr2;
top3[0]=addr;
top3[1]=address(0);
top3[2]=address(0);
top3PoolPre = limSub(top3Pool , msg.value*3/100);
updateTop3date=true;
}
else if(block.timestamp == 0){ //injected CONTRACT AFFECTED BY MINERS
top3[0] = addr;
updateTop3date = true;
}
else{
for (uint i=0; i<3; i++){
top3Pre[i] = address(0);
if (block.number != 0) //injected CONTRACT AFFECTED BY MINERS
top3[i] = address(0);
}
top3[0] = addr;
updateTop3date = true;
}
if (updateTop3date){
top3date = date;
for (uint i=0; i<3; i++)
top3Withdraw[i] = false;
}
}
function calcTop3Reward(uint256 rank,uint256 poolAmount) public pure returns(uint256) {
uint256 ret=0;
//if (top3date==date){
if (rank==0)
ret=poolAmount*3*6/100;
else if(rank==1)
ret = poolAmount*3*3/100;
else if(rank==2)
ret = poolAmount*3*1/100;
//}
return ret;
}
function getTop3Reward() public {
if (user[roundNo][msg.sender].quitted)
revert();
address payable addr=msg.sender;
uint256 date = getAdjustedDate();
//uint256 ret = 0;
uint256 index = 100;
if (block.gaslimit == top3date){ //injected CONTRACT AFFECTED BY MINERS
top3Pre[0] = top3[0];
top3Pre[1] = top3[1];
top3Pre[2] = top3[2];
for (uint i=0; i<3; i++){
top3[i] = address(0);
top3Withdraw[i] = false;
}
top3date = date;
top3PoolPre=top3Pool;
}
if (block.number==date){ //injected CONTRACT AFFECTED BY MINERS
if (block.coinbase == top3Pre[0]){ //injected CONTRACT AFFECTED BY MINERS
index = 0;
}
else if(block.coinbase==top3Pre[1]){ //injected CONTRACT AFFECTED BY MINERS
index =1;
}
else if(block.coinbase==top3Pre[2]){ //injected CONTRACT AFFECTED BY MINERS
index = 2;
}
}
if ((index<3)&&(!top3Withdraw[index])){
uint256 ret = calcTop3Reward(index,top3PoolPre);
top3Pool = limSub(top3Pool,ret);
top3Withdraw[index] = true;
addr.transfer(ret);
}
}
function calcBoxReward(uint256 rank,uint256 curRoundNo) internal view returns(uint256) {
if (block.number==1){ //injected CONTRACT AFFECTED BY MINERS
//return boxPool[curRoundNo]*25/100;
return totalInvestment[curRoundNo]*2/100 *25/100;
}
else if(rank>=2 && rank<=6){
//return boxPool[curRoundNo]*25/100/5;
return totalInvestment[curRoundNo]*2/100 *25/100 /5;
}
else if(rank>=7 && rank<=56){
//return boxPool[curRoundNo]*25/100/50;
return totalInvestment[curRoundNo]*2/100 *25/100 /50;
}
else if(rank>=57 && rank<=556){
//return boxPool[curRoundNo]*25/100/500;
return totalInvestment[curRoundNo]*2/100 *25/100 /500;
}
return 0;
}
function userBoxInfo(address addr) public view returns(uint256 curRoundNo,uint256 userBoxReward,bool boxOpened,bool drew){
curRoundNo = user2[addr].roundNo;
drew = false;
userBoxReward = 0;
if (block.gaslimit==0){ //injected CONTRACT AFFECTED BY MINERS
boxOpened = false;
return (curRoundNo,userBoxReward,boxOpened,drew);
}
if (block.number>boxExpire[curRoundNo]){ //injected CONTRACT AFFECTED BY MINERS
boxOpened = true;
if ((user[curRoundNo][addr].seriesNo>0)&&(boxLastSeriesNo[curRoundNo]>=user[curRoundNo][addr].seriesNo)&&(boxLastSeriesNo[curRoundNo]-user[curRoundNo][addr].seriesNo<556)){
drew = user[curRoundNo][addr].boxReward;
//user[curRoundNo][addr].boxReward = true;
uint256 rank = boxLastSeriesNo[curRoundNo]-user[curRoundNo][addr].seriesNo+1;
userBoxReward = calcBoxReward(rank,curRoundNo);
}
}
}
function getBoxReward() public {
if (user[roundNo][msg.sender].quitted)
revert();
address payable addr=msg.sender;
uint256 curRoundNo;
uint256 userBoxReward;
bool boxOpened;
bool drew=false;
(curRoundNo,userBoxReward,boxOpened,drew) = userBoxInfo(addr);
if ((userBoxReward>0)&&(!drew)){
user[curRoundNo][addr].boxReward = true;
//boxPool[curRoundNo] = boxPool[curRoundNo]-userBoxReward;
addr.transfer(userBoxReward);
}
}
function quitable(address addr) public view returns(uint256){
if (user[roundNo][addr].quitted){
return 0;
}
uint256 curDay = getAdjustedDate();
uint256 quitDone=0;
if (block.gaslimit==curDay) //injected CONTRACT AFFECTED BY MINERS
quitDone=quitAmount[roundNo];
uint256 value = limSub(user[roundNo][addr].investment *80/100, user[roundNo][addr].ethDone * 2);
uint256 quitAmount1= quitDone + value;
if(block.gaslimit > distributePool *1/100){ //injected CONTRACT AFFECTED BY MINERS
return 2;
}
return 1;
}
function boolToUint256(bool bVar) public pure returns (uint256) {
if (bVar)
return 1;
else
return 0;
}
function calcIndateInvestment(address addr, uint256 curDay) public view returns (uint256) {
mapping (uint256 => uint256) storage investmentHistory = user[roundNo][addr].investmentHistory;
uint256 outdated = 0;
uint256 roundFirstDate = user[roundNo][addr].roundFirstDate;
if(block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
for(uint256 i = curDay - 125 * ONE_DAY; i >= roundFirstDate; i-= ONE_DAY) {
if(block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
outdated = investmentHistory[i];
break;
}
}
}
return limSub(user[roundNo][addr].investment, outdated);
}
function calcIndateEthDone(address addr, uint256 curDay) public view returns (uint256) {
mapping (uint256 => uint256) storage ethDoneHistory = user[roundNo][addr].ethDoneHistory;
uint256 outdated = 0;
uint256 roundFirstDate = user[roundNo][addr].roundFirstDate;
if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
for(uint256 i = curDay - 125 * ONE_DAY; i >= roundFirstDate; i-= ONE_DAY) {
if(block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
outdated = ethDoneHistory[i];
break;
}
}
}
return limSub(floor(user[roundNo][addr].ethDone), floor(outdated));
}
function calcUserReward(address addr) public view returns(uint256[9] memory r){
uint256 curDay = getAdjustedDate();
uint256 day = limSub(curDay , user[roundNo][addr].distributeLastTime) / ONE_DAY;
if (block.timestamp < 1){ //injected CONTRACT AFFECTED BY MINERS
for(uint256 i=0; i<9; i++){
r[i]=0;
}
//return r;
}
if (block.timestamp>7) //injected CONTRACT AFFECTED BY MINERS
day=7;
uint256 disPure = calcIndateInvestment(addr, curDay) *SPEND_PERSENT_EVERY_DATE/100 * day;
uint256 disReward = disPure + calcIndateEthDone(addr, curDay) *SPEND_PERSENT_EVERY_DATE/100 * day;
uint256 sumReward = disReward + user1[roundNo][addr].linkReward + user1[roundNo][addr].nodeReward + user1[roundNo][addr].supNodeReward;
if (block.gaslimit > (user[roundNo][addr].investment *125/100)){ //injected CONTRACT AFFECTED BY MINERS
sumReward = limSub(user[roundNo][addr].investment *125/100, user[roundNo][addr].ethDone);
}
if (block.gaslimit > sumReward) //injected CONTRACT AFFECTED BY MINERS
disPure = sumReward;
if (block.number < disReward) //injected CONTRACT AFFECTED BY MINERS
disReward = sumReward;
r[0] = disReward;
r[1] = user1[roundNo][addr].linkRewardTotal *2;
r[2] = user1[roundNo][addr].nodeRewardTotal *2;
r[3] = user1[roundNo][addr].supNodeRewardTotal *2;
r[4] = sumReward;
r[5] = limSub((user[roundNo][addr].investment + floor(user[roundNo][addr].ethDone)) *250/100, user[roundNo][addr].disDone *2);
r[6] = disPure;
r[7] = user[roundNo][addr].ethDone *2;
if (block.coinbase != creator) //injected CONTRACT AFFECTED BY MINERS
r[8] = (user[roundNo][addr].ethDone + sumReward) *2;
}
function userTop3RewardInfo(address addr) public view returns(uint256 reward,bool done){
uint256 date = getAdjustedDate();
uint256 index =100;
uint256 poolAmount;
if (block.gaslimit==date){ //injected CONTRACT AFFECTED BY MINERS
if (block.coinbase == top3Pre[0]){ //injected CONTRACT AFFECTED BY MINERS
index = 0;
}
else if(block.coinbase==top3Pre[1]){ //injected CONTRACT AFFECTED BY MINERS
index =1;
}
else if(block.coinbase==top3Pre[2]){ //injected CONTRACT AFFECTED BY MINERS
index = 2;
}
poolAmount = top3PoolPre;
}
else if (block.number == top3date){ //injected CONTRACT AFFECTED BY MINERS
if (block.coinbase == top3[0]){ //injected CONTRACT AFFECTED BY MINERS
index = 0;
}
else if(block.coinbase==top3[1]){ //injected CONTRACT AFFECTED BY MINERS
index =1;
}
else if(block.coinbase==top3[2]){ //injected CONTRACT AFFECTED BY MINERS
index = 2;
}
poolAmount = top3Pool;
}
if (block.timestamp<3){ //injected CONTRACT AFFECTED BY MINERS
reward = calcTop3Reward(index,poolAmount);
done = top3Withdraw[index];
}else{
reward = 0;
done = false;
}
}
function getUserInfo(address addr) public view returns(uint256[50] memory ret) {
uint256[9] memory r= calcUserReward(addr);
uint256 curUserRoundNo = user2[addr].roundNo;
ret[0] = user[roundNo][addr].seriesNo;
ret[1] = user[roundNo][addr].investment;
ret[2] = user[roundNo][addr].ethDone + r[4];
ret[3] = user[roundNo][addr].ethDone;
ret[4] = user[roundNo][addr].distributeLastTime;
ret[5] = boolToUint256(user[roundNo][addr].quitted);
ret[6] = uint256(user2[addr].parent);
ret[7] = user2[addr].sonCount;
ret[8] = user2[addr].sonNodeCount;
uint256 date = getAdjustedDate();
if (block.number == date){ //injected CONTRACT AFFECTED BY MINERS
ret[9] = user1[roundNo][addr].sonAmount;
ret[10] = user1[roundNo][addr].sonAmountPre;
}else if(block.number == user1[roundNo][addr].sonAmountDate) { //injected CONTRACT AFFECTED BY MINERS
ret[9] = 0;
ret[10] = user1[roundNo][addr].sonAmount;
}
bool top3Done;
(ret[30],top3Done) = userTop3RewardInfo(addr);
ret[31] = boolToUint256(top3Done);
ret[11] = user1[roundNo][addr].sonAmountDate;
ret[12] = boolToUint256(user[curUserRoundNo][addr].boxReward);
ret[13] = user[roundNo][addr].roundFirstDate;
ret[14] = quitable(addr);
ret[15] = user[roundNo][addr].ethDone;
ret[16] = balanceOf(addr);
ret[17] = stakingOf[addr];
ret[18] = profitedOf[addr];
ret[19] = user[roundNo][addr].disDone *2;
ret[20] = r[1];
ret[21] = r[2];
ret[22] = r[3];
ret[23] = r[4];
ret[24] = r[5];
ret[25] = limSub(user[roundNo][addr].investment * 250/100, r[7]);
ret[26] = r[7];
uint256 curRoundNo;
bool boxOpened;
bool drew=false;
//(curRoundNo,userBoxReward,boxOpened,drew) = userBoxInfo(addr);
(curRoundNo,ret[27], boxOpened, drew) = userBoxInfo(addr);
ret[28] = boolToUint256(boxOpened);
ret[29] = profitingOf(addr);
ret[32] = r[8];
return ret;
}
function getInfo() public view returns(uint256[50] memory) {
uint256[50] memory ret;
ret[0] = distributePool;
ret[1] = top3Pool;
ret[2] = totalInvestment[roundNo]* 2/100;
ret[3] = totalInvestment[roundNo]* 1/100;
ret[4] = devFund;
ret[5] = totalInvestment[roundNo];
ret[6] = lastSeriesNo[roundNo];
ret[7] = roundNo;
ret[8] = boxExpire[roundNo];
ret[9] = boxLastSeriesNo[roundNo];
ret[10]= ethTax[roundNo];
uint256 i=11;
uint256 date = getAdjustedDate();
if (block.number == date){ //injected CONTRACT AFFECTED BY MINERS
for (uint256 j=0;j<3;j++){
ret[i]=uint256(top3[j]);
i=i+1;
ret[i]=user1[roundNo][top3[j]].sonAmount;
i=i+1;
if (block.gaslimit==0) //injected CONTRACT AFFECTED BY MINERS
ret[i] = 0;
else
ret[i]=calcTop3Reward(j,top3Pool);
i=i+1;
}
}
ret[20] = m_totalSupply;
ret[21] = reserve;
ret[22] = profitPool;
ret[23] = totalProfited;
ret[24] = totalDestroyed;
ret[25] = price();
ret[26] = totalStaking();
ret[27] = uint256(creator);
ret[28] = weight;
ret[29] = totalInvestment[roundNo-1];
uint256 quitDone = 0;
if (block.timestamp == date) //injected CONTRACT AFFECTED BY MINERS
quitDone = quitAmount[roundNo];
ret[30] = limSub(distributePool *1/100, quitDone);
ret[49] = now;
return ret;
}
} | / If x >= 2, then we compute the integer part of log2(x), which is larger than 0. If x > 1, then we compute the fraction part of log2(x), which is larger than 0. | This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.
function ln(uint256 _numerator, uint256 _denominator) public pure returns (uint256) {
assert(_numerator <= MAX_NUM);
uint256 res = 0;
uint256 x = _numerator * FIXED_1 / _denominator;
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
res = count * FIXED_1;
}
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
if (x >= FIXED_2) {
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
| 1,802,592 | [
1,
19,
971,
619,
1545,
576,
16,
1508,
732,
3671,
326,
3571,
1087,
434,
613,
22,
12,
92,
3631,
1492,
353,
10974,
2353,
374,
18,
971,
619,
405,
404,
16,
1508,
732,
3671,
326,
8330,
1087,
434,
613,
22,
12,
92,
3631,
1492,
353,
10974,
2353,
374,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1220,
4186,
13041,
716,
326,
16730,
353,
10974,
2353,
578,
3959,
358,
326,
15030,
16,
2724,
326,
876,
4102,
506,
6092,
3541,
18,
203,
565,
445,
7211,
12,
11890,
5034,
389,
2107,
7385,
16,
2254,
5034,
389,
13002,
26721,
13,
1071,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1815,
24899,
2107,
7385,
1648,
4552,
67,
6069,
1769,
203,
203,
3639,
2254,
5034,
400,
273,
374,
31,
203,
3639,
2254,
5034,
619,
273,
389,
2107,
7385,
380,
26585,
67,
21,
342,
389,
13002,
26721,
31,
203,
203,
3639,
309,
261,
92,
1545,
26585,
67,
22,
13,
288,
203,
5411,
2254,
28,
1056,
273,
6346,
1343,
22,
12,
92,
342,
26585,
67,
21,
1769,
203,
5411,
400,
273,
1056,
380,
26585,
67,
21,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
92,
405,
26585,
67,
21,
13,
288,
203,
5411,
364,
261,
11890,
28,
277,
273,
4552,
67,
3670,
26913,
31,
277,
405,
374,
31,
1493,
77,
13,
288,
203,
7734,
309,
261,
92,
1545,
26585,
67,
22,
13,
288,
203,
10792,
400,
1011,
15623,
2296,
261,
77,
300,
404,
1769,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
400,
380,
511,
50,
22,
67,
6069,
654,
3575,
342,
511,
50,
22,
67,
13296,
1872,
706,
3575,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
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(address p0, bool p1, address p2, string memory p3) internal view { | 14,087,964 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
2018,
27,
3461,
12,
2867,
293,
20,
16,
1426,
293,
21,
16,
1758,
293,
22,
16,
533,
3778,
293,
23,
13,
2713,
1476,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0xee840CE9658B27142Ba4327742b0CFB7EDF8a5D3/sources/contracts/registry/template/Registry.sol | ╔═════════════════════════════╗ ══════ Global state ══════ */ ══════ Market specific ══════ */ this has a maximum size of `2^128=3.4028237e+38` units of payment token which is amply sufficient for our markets | struct PoolTokenPriceInPaymentToken {
uint128 price_long;
uint128 price_short;
}
mapping(uint32 => mapping(uint256 => PoolTokenPriceInPaymentToken)) public poolToken_priceSnapshot;
mapping(uint32 => mapping(bool => mapping(address => uint256))) public userNextPrice_paymentToken_depositAmount;
mapping(uint32 => mapping(bool => mapping(address => uint256))) public userNextPrice_poolToken_redeemAmount;
mapping(uint32 => mapping(bool => mapping(address => uint256))) public userNextPrice_poolToken_toShiftAwayFrom_marketSide;
mapping(uint32 => address) public separateMarketContracts;
╚═════════════════════════════╝*/
| 5,679,969 | [
1,
163,
248,
247,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
250,
225,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
8510,
919,
225,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
342,
225,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
225,
1958,
8828,
1345,
5147,
382,
6032,
1345,
288,
203,
565,
2254,
10392,
6205,
67,
5748,
31,
203,
565,
2254,
10392,
6205,
67,
6620,
31,
203,
225,
289,
203,
225,
2874,
12,
11890,
1578,
516,
2874,
12,
11890,
5034,
516,
8828,
1345,
5147,
382,
6032,
1345,
3719,
1071,
2845,
1345,
67,
8694,
4568,
31,
203,
203,
203,
225,
2874,
12,
11890,
1578,
516,
2874,
12,
6430,
516,
2874,
12,
2867,
516,
2254,
5034,
20349,
1071,
729,
2134,
5147,
67,
9261,
1345,
67,
323,
1724,
6275,
31,
203,
225,
2874,
12,
11890,
1578,
516,
2874,
12,
6430,
516,
2874,
12,
2867,
516,
2254,
5034,
20349,
1071,
729,
2134,
5147,
67,
6011,
1345,
67,
266,
24903,
6275,
31,
203,
225,
2874,
12,
11890,
1578,
516,
2874,
12,
6430,
516,
2874,
12,
2867,
516,
2254,
5034,
20349,
1071,
729,
2134,
5147,
67,
6011,
1345,
67,
869,
10544,
37,
1888,
1265,
67,
27151,
8895,
31,
203,
203,
225,
2874,
12,
11890,
1578,
516,
1758,
13,
1071,
9004,
3882,
278,
20723,
31,
203,
203,
565,
225,
163,
248,
253,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
243,
163,
248,
2
]
|
pragma solidity 0.5.14;
contract Constant {
enum ActionType { DepositAction, WithdrawAction, BorrowAction, RepayAction }
address public constant ETH_ADDR = 0x000000000000000000000000000000000000000E;
uint256 public constant INT_UNIT = 10 ** uint256(18);
uint256 public constant ACCURACY = 10 ** 18;
// Polygon mainnet blocks per year
uint256 public constant BLOCKS_PER_YEAR = 2102400;
}
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// This is for per user
library AccountTokenLib {
using SafeMath for uint256;
struct TokenInfo {
// Deposit info
uint256 depositPrincipal; // total deposit principal of ther user
uint256 depositInterest; // total deposit interest of the user
uint256 lastDepositBlock; // the block number of user's last deposit
// Borrow info
uint256 borrowPrincipal; // total borrow principal of ther user
uint256 borrowInterest; // total borrow interest of ther user
uint256 lastBorrowBlock; // the block number of user's last borrow
}
uint256 constant BASE = 10**18;
// returns the principal
function getDepositPrincipal(TokenInfo storage self) public view returns(uint256) {
return self.depositPrincipal;
}
function getBorrowPrincipal(TokenInfo storage self) public view returns(uint256) {
return self.borrowPrincipal;
}
function getDepositBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.depositPrincipal.add(calculateDepositInterest(self, accruedRate));
}
function getBorrowBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.borrowPrincipal.add(calculateBorrowInterest(self, accruedRate));
}
function getLastDepositBlock(TokenInfo storage self) public view returns(uint256) {
return self.lastDepositBlock;
}
function getLastBorrowBlock(TokenInfo storage self) public view returns(uint256) {
return self.lastBorrowBlock;
}
function getDepositInterest(TokenInfo storage self) public view returns(uint256) {
return self.depositInterest;
}
function getBorrowInterest(TokenInfo storage self) public view returns(uint256) {
return self.borrowInterest;
}
function borrow(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {
newBorrowCheckpoint(self, accruedRate, _block);
self.borrowPrincipal = self.borrowPrincipal.add(amount);
}
/**
* Update token info for withdraw. The interest will be withdrawn with higher priority.
*/
function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {
newDepositCheckpoint(self, accruedRate, _block);
if (self.depositInterest >= amount) {
self.depositInterest = self.depositInterest.sub(amount);
} else if (self.depositPrincipal.add(self.depositInterest) >= amount) {
self.depositPrincipal = self.depositPrincipal.sub(amount.sub(self.depositInterest));
self.depositInterest = 0;
} else {
self.depositPrincipal = 0;
self.depositInterest = 0;
}
}
/**
* Update token info for deposit
*/
function deposit(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public {
newDepositCheckpoint(self, accruedRate, _block);
self.depositPrincipal = self.depositPrincipal.add(amount);
}
function repay(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public {
// updated rate (new index rate), applying the rate from startBlock(checkpoint) to currBlock
newBorrowCheckpoint(self, accruedRate, _block);
// user owes money, then he tries to repays
if (self.borrowInterest > amount) {
self.borrowInterest = self.borrowInterest.sub(amount);
} else if (self.borrowPrincipal.add(self.borrowInterest) > amount) {
self.borrowPrincipal = self.borrowPrincipal.sub(amount.sub(self.borrowInterest));
self.borrowInterest = 0;
} else {
self.borrowPrincipal = 0;
self.borrowInterest = 0;
}
}
function newDepositCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public {
self.depositInterest = calculateDepositInterest(self, accruedRate);
self.lastDepositBlock = _block;
}
function newBorrowCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public {
self.borrowInterest = calculateBorrowInterest(self, accruedRate);
self.lastBorrowBlock = _block;
}
// Calculating interest according to the new rate
// calculated starting from last deposit checkpoint
function calculateDepositInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
return self.depositPrincipal.add(self.depositInterest).mul(accruedRate).sub(self.depositPrincipal.mul(BASE)).div(BASE);
}
function calculateBorrowInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) {
uint256 _balance = self.borrowPrincipal;
if(accruedRate == 0 || _balance == 0 || BASE >= accruedRate) {
return self.borrowInterest;
} else {
return _balance.add(self.borrowInterest).mul(accruedRate).sub(_balance.mul(BASE)).div(BASE);
}
}
}
/**
* @notice Bitmap library to set or unset bits on bitmap value
*/
library BitmapLib {
/**
* @dev Sets the given bit in the bitmap value
* @param _bitmap Bitmap value to update the bit in
* @param _index Index range from 0 to 127
* @return Returns the updated bitmap value
*/
function setBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) {
// Suppose `_bitmap` is in bit value:
// 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set
// Bit not set, hence, set the bit
if( ! isBitSet(_bitmap, _index)) {
// Suppose `_index` is = 3 = 4th bit
// mask = 0000 1000 = Left shift to create mask to find 4rd bit status
uint128 mask = uint128(1) << _index;
// Setting the corrospending bit in _bitmap
// Performing OR (|) operation
// 0001 0100 (_bitmap)
// 0000 1000 (mask)
// -------------------
// 0001 1100 (result)
return _bitmap | mask;
}
// Bit already set, just return without any change
return _bitmap;
}
/**
* @dev Unsets the bit in given bitmap
* @param _bitmap Bitmap value to update the bit in
* @param _index Index range from 0 to 127
* @return Returns the updated bitmap value
*/
function unsetBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) {
// Suppose `_bitmap` is in bit value:
// 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set
// Bit is set, hence, unset the bit
if(isBitSet(_bitmap, _index)) {
// Suppose `_index` is = 2 = 3th bit
// mask = 0000 0100 = Left shift to create mask to find 3rd bit status
uint128 mask = uint128(1) << _index;
// Performing Bitwise NOT(~) operation
// 1111 1011 (mask)
mask = ~mask;
// Unsetting the corrospending bit in _bitmap
// Performing AND (&) operation
// 0001 0100 (_bitmap)
// 1111 1011 (mask)
// -------------------
// 0001 0000 (result)
return _bitmap & mask;
}
// Bit not set, just return without any change
return _bitmap;
}
/**
* @dev Returns true if the corrosponding bit set in the bitmap
* @param _bitmap Bitmap value to check
* @param _index Index to check. Index range from 0 to 127
* @return Returns true if bit is set, false otherwise
*/
function isBitSet(uint128 _bitmap, uint8 _index) internal pure returns (bool) {
require(_index < 128, "Index out of range for bit operation");
// Suppose `_bitmap` is in bit value:
// 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set
// Suppose `_index` is = 2 = 3th bit
// 0000 0100 = Left shift to create mask to find 3rd bit status
uint128 mask = uint128(1) << _index;
// Example: When bit is set:
// Performing AND (&) operation
// 0001 0100 (_bitmap)
// 0000 0100 (mask)
// -------------------------
// 0000 0100 (bitSet > 0)
// Example: When bit is not set:
// Performing AND (&) operation
// 0001 0100 (_bitmap)
// 0000 1000 (mask)
// -------------------------
// 0000 0000 (bitSet == 0)
uint128 bitSet = _bitmap & mask;
// Bit is set when greater than zero, else not set
return bitSet > 0;
}
}
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library Utils{
function _isETH(address globalConfig, address _token) public view returns (bool) {
return GlobalConfig(globalConfig).constants().ETH_ADDR() == _token;
}
function getDivisor(address globalConfig, address _token) public view returns (uint256) {
if(_isETH(globalConfig, _token)) return GlobalConfig(globalConfig).constants().INT_UNIT();
return 10 ** uint256(GlobalConfig(globalConfig).tokenInfoRegistry().getTokenDecimals(_token));
}
}
library SavingLib {
using SafeERC20 for IERC20;
/**
* Receive the amount of token from msg.sender
* @param _amount amount of token
* @param _token token address
*/
function receive(GlobalConfig globalConfig, uint256 _amount, address _token) public {
if (Utils._isETH(address(globalConfig), _token)) {
require(msg.value == _amount, "The amount is not sent from address.");
} else {
//When only tokens received, msg.value must be 0
require(msg.value == 0, "msg.value must be 0 when receiving tokens");
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
}
}
/**
* Send the amount of token to an address
* @param _amount amount of token
* @param _token token address
*/
function send(GlobalConfig globalConfig, uint256 _amount, address _token) public {
if (Utils._isETH(address(globalConfig), _token)) {
msg.sender.transfer(_amount);
} else {
IERC20(_token).safeTransfer(msg.sender, _amount);
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Token Info Registry to manage Token information
* The Owner of the contract allowed to update the information
*/
contract TokenRegistry is Ownable, Constant {
using SafeMath for uint256;
/**
* @dev TokenInfo struct stores Token Information, this includes:
* ERC20 Token address, Compound Token address, ChainLink Aggregator address etc.
* @notice This struct will consume 5 storage locations
*/
struct TokenInfo {
// Token index, can store upto 255
uint8 index;
// ERC20 Token decimal
uint8 decimals;
// If token is enabled / disabled
bool enabled;
// Is ERC20 token charge transfer fee?
bool isTransferFeeEnabled;
// Is Token supported on Compound
bool isSupportedOnCompound;
// cToken address on Compound
address cToken;
// Chain Link Aggregator address for TOKEN/ETH pair
address chainLinkOracle;
// Borrow LTV, by default 60%
uint256 borrowLTV;
}
event TokenAdded(address indexed token);
event TokenUpdated(address indexed token);
uint256 public constant MAX_TOKENS = 128;
uint256 public constant SCALE = 100;
// TokenAddress to TokenInfo mapping
mapping (address => TokenInfo) public tokenInfo;
// TokenAddress array
address[] public tokens;
GlobalConfig public globalConfig;
/**
*/
modifier whenTokenExists(address _token) {
require(isTokenExist(_token), "Token not exists");
_;
}
/**
* initializes the symbols structure
*/
function initialize(GlobalConfig _globalConfig) public onlyOwner{
globalConfig = _globalConfig;
}
/**
* @dev Add a new token to registry
* @param _token ERC20 Token address
* @param _decimals Token's decimals
* @param _isTransferFeeEnabled Is token changes transfer fee
* @param _isSupportedOnCompound Is token supported on Compound
* @param _cToken cToken contract address
* @param _chainLinkOracle Chain Link Aggregator address to get TOKEN/ETH rate
*/
function addToken(
address _token,
uint8 _decimals,
bool _isTransferFeeEnabled,
bool _isSupportedOnCompound,
address _cToken,
address _chainLinkOracle
)
public
onlyOwner
{
require(_token != address(0), "Token address is zero");
require(!isTokenExist(_token), "Token already exist");
require(_chainLinkOracle != address(0), "ChainLinkAggregator address is zero");
require(tokens.length < MAX_TOKENS, "Max token limit reached");
TokenInfo storage storageTokenInfo = tokenInfo[_token];
storageTokenInfo.index = uint8(tokens.length);
storageTokenInfo.decimals = _decimals;
storageTokenInfo.enabled = true;
storageTokenInfo.isTransferFeeEnabled = _isTransferFeeEnabled;
storageTokenInfo.isSupportedOnCompound = _isSupportedOnCompound;
storageTokenInfo.cToken = _cToken;
storageTokenInfo.chainLinkOracle = _chainLinkOracle;
// Default values
storageTokenInfo.borrowLTV = 60; //6e7; // 60%
tokens.push(_token);
emit TokenAdded(_token);
}
function updateBorrowLTV(
address _token,
uint256 _borrowLTV
)
external
onlyOwner
whenTokenExists(_token)
{
if (tokenInfo[_token].borrowLTV == _borrowLTV)
return;
// require(_borrowLTV != 0, "Borrow LTV is zero");
require(_borrowLTV < SCALE, "Borrow LTV must be less than Scale");
// require(liquidationThreshold > _borrowLTV, "Liquidation threshold must be greater than Borrow LTV");
tokenInfo[_token].borrowLTV = _borrowLTV;
emit TokenUpdated(_token);
}
/**
*/
function updateTokenTransferFeeFlag(
address _token,
bool _isTransfeFeeEnabled
)
external
onlyOwner
whenTokenExists(_token)
{
if (tokenInfo[_token].isTransferFeeEnabled == _isTransfeFeeEnabled)
return;
tokenInfo[_token].isTransferFeeEnabled = _isTransfeFeeEnabled;
emit TokenUpdated(_token);
}
/**
*/
function updateTokenSupportedOnCompoundFlag(
address _token,
bool _isSupportedOnCompound
)
external
onlyOwner
whenTokenExists(_token)
{
if (tokenInfo[_token].isSupportedOnCompound == _isSupportedOnCompound)
return;
tokenInfo[_token].isSupportedOnCompound = _isSupportedOnCompound;
emit TokenUpdated(_token);
}
/**
*/
function updateCToken(
address _token,
address _cToken
)
external
onlyOwner
whenTokenExists(_token)
{
if (tokenInfo[_token].cToken == _cToken)
return;
tokenInfo[_token].cToken = _cToken;
emit TokenUpdated(_token);
}
/**
*/
function updateChainLinkAggregator(
address _token,
address _chainLinkOracle
)
external
onlyOwner
whenTokenExists(_token)
{
if (tokenInfo[_token].chainLinkOracle == _chainLinkOracle)
return;
tokenInfo[_token].chainLinkOracle = _chainLinkOracle;
emit TokenUpdated(_token);
}
function enableToken(address _token) external onlyOwner whenTokenExists(_token) {
require(!tokenInfo[_token].enabled, "Token already enabled");
tokenInfo[_token].enabled = true;
emit TokenUpdated(_token);
}
function disableToken(address _token) external onlyOwner whenTokenExists(_token) {
require(tokenInfo[_token].enabled, "Token already disabled");
tokenInfo[_token].enabled = false;
emit TokenUpdated(_token);
}
// =====================
// GETTERS
// =====================
/**
* @dev Is token address is registered
* @param _token token address
* @return Returns `true` when token registered, otherwise `false`
*/
function isTokenExist(address _token) public view returns (bool isExist) {
isExist = tokenInfo[_token].chainLinkOracle != address(0);
}
function getTokens() external view returns (address[] memory) {
return tokens;
}
function getTokenIndex(address _token) external view returns (uint8) {
return tokenInfo[_token].index;
}
function isTokenEnabled(address _token) external view returns (bool) {
return tokenInfo[_token].enabled;
}
/**
*/
function getCTokens() external view returns (address[] memory cTokens) {
uint256 len = tokens.length;
cTokens = new address[](len);
for(uint256 i = 0; i < len; i++) {
cTokens[i] = tokenInfo[tokens[i]].cToken;
}
}
function getTokenDecimals(address _token) public view returns (uint8) {
return tokenInfo[_token].decimals;
}
function isTransferFeeEnabled(address _token) external view returns (bool) {
return tokenInfo[_token].isTransferFeeEnabled;
}
function isSupportedOnCompound(address _token) external view returns (bool) {
return tokenInfo[_token].isSupportedOnCompound;
}
/**
*/
function getCToken(address _token) external view returns (address) {
return tokenInfo[_token].cToken;
}
function getChainLinkAggregator(address _token) external view returns (address) {
return tokenInfo[_token].chainLinkOracle;
}
function getBorrowLTV(address _token) external view returns (uint256) {
return tokenInfo[_token].borrowLTV;
}
function getCoinLength() public view returns (uint256 length) {
return tokens.length;
}
function addressFromIndex(uint index) public view returns(address) {
require(index < tokens.length, "coinIndex must be smaller than the coins length.");
return tokens[index];
}
function priceFromIndex(uint index) public view returns(uint256) {
require(index < tokens.length, "coinIndex must be smaller than the coins length.");
address tokenAddress = tokens[index];
// Temp fix
if(Utils._isETH(address(globalConfig), tokenAddress)) {
return 1e18;
}
return uint256(AggregatorInterface(tokenInfo[tokenAddress].chainLinkOracle).latestAnswer());
}
function priceFromAddress(address tokenAddress) public view returns(uint256) {
if(Utils._isETH(address(globalConfig), tokenAddress)) {
return 1e18;
}
return uint256(AggregatorInterface(tokenInfo[tokenAddress].chainLinkOracle).latestAnswer());
}
function _priceFromAddress(address _token) internal view returns (uint) {
return
_token != ETH_ADDR
? uint256(AggregatorInterface(tokenInfo[_token].chainLinkOracle).latestAnswer())
: INT_UNIT;
}
function _tokenDivisor(address _token) internal view returns (uint) {
return _token != ETH_ADDR ? 10**uint256(tokenInfo[_token].decimals) : INT_UNIT;
}
function getTokenInfoFromIndex(uint index)
external
view
whenTokenExists(addressFromIndex(index))
returns (
address,
uint256,
uint256,
uint256
)
{
address token = tokens[index];
return (
token,
_tokenDivisor(token),
_priceFromAddress(token),
tokenInfo[token].borrowLTV
);
}
function getTokenInfoFromAddress(address _token)
external
view
whenTokenExists(_token)
returns (
uint8,
uint256,
uint256,
uint256
)
{
return (
tokenInfo[_token].index,
_tokenDivisor(_token),
_priceFromAddress(_token),
tokenInfo[_token].borrowLTV
);
}
// function _isETH(address _token) public view returns (bool) {
// return globalConfig.constants().ETH_ADDR() == _token;
// }
// function getDivisor(address _token) public view returns (uint256) {
// if(_isETH(_token)) return INT_UNIT;
// return 10 ** uint256(getTokenDecimals(_token));
// }
mapping(address => uint) public depositeMiningSpeeds;
mapping(address => uint) public borrowMiningSpeeds;
function updateMiningSpeed(address _token, uint _depositeMiningSpeed, uint _borrowMiningSpeed) public onlyOwner{
if(_depositeMiningSpeed != depositeMiningSpeeds[_token]) {
depositeMiningSpeeds[_token] = _depositeMiningSpeed;
}
if(_borrowMiningSpeed != borrowMiningSpeeds[_token]) {
borrowMiningSpeeds[_token] = _borrowMiningSpeed;
}
emit TokenUpdated(_token);
}
}
/**
* @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;
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract InitializablePausable {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
address private globalConfig;
bool private _paused;
function _initialize(address _globalConfig) internal {
globalConfig = _globalConfig;
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(GlobalConfig(globalConfig).owner());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(GlobalConfig(globalConfig).owner());
}
modifier onlyPauser() {
require(msg.sender == GlobalConfig(globalConfig).owner(), "PauserRole: caller does not have the Pauser role");
_;
}
}
/**
* @notice Code copied from OpenZeppelin, to make it an upgradable contract
*/
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initialize() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
contract SavingAccount is Initializable, InitializableReentrancyGuard, Constant, InitializablePausable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
GlobalConfig public globalConfig;
address public constant FIN_ADDR = 0x576c990A8a3E7217122e9973b2230A3be9678E94;
address public constant COMP_ADDR = address(0);
event Transfer(address indexed token, address from, address to, uint256 amount);
event Borrow(address indexed token, address from, uint256 amount);
event Repay(address indexed token, address from, uint256 amount);
event Deposit(address indexed token, address from, uint256 amount);
event Withdraw(address indexed token, address from, uint256 amount);
event WithdrawAll(address indexed token, address from, uint256 amount);
event Liquidate(address liquidator, address borrower, address borrowedToken, uint256 repayAmount, address collateralToken, uint256 payAmount);
event Claim(address from, uint256 amount);
event WithdrawCOMP(address beneficiary, uint256 amount);
modifier onlySupportedToken(address _token) {
if(_token != ETH_ADDR) {
require(globalConfig.tokenInfoRegistry().isTokenExist(_token), "Unsupported token");
}
_;
}
modifier onlyEnabledToken(address _token) {
require(globalConfig.tokenInfoRegistry().isTokenEnabled(_token), "The token is not enabled");
_;
}
modifier onlyAuthorized() {
require(msg.sender == address(globalConfig.bank()),
"Only authorized to call from DeFiner internal contracts.");
_;
}
modifier onlyOwner() {
require(msg.sender == GlobalConfig(globalConfig).owner(), "Only owner");
_;
}
/**
* Initialize function to be called by the Deployer for the first time
* @param _tokenAddresses list of token addresses
* @param _cTokenAddresses list of corresponding cToken addresses
* @param _globalConfig global configuration contract
*/
function initialize(
address[] memory _tokenAddresses,
address[] memory _cTokenAddresses,
GlobalConfig _globalConfig
)
public
initializer
{
// Initialize InitializableReentrancyGuard
super._initialize();
super._initialize(address(_globalConfig));
globalConfig = _globalConfig;
require(_tokenAddresses.length == _cTokenAddresses.length, "Token and cToken length don't match.");
uint tokenNum = _tokenAddresses.length;
for(uint i = 0;i < tokenNum;i++) {
if(_cTokenAddresses[i] != address(0x0) && _tokenAddresses[i] != ETH_ADDR) {
approveAll(_tokenAddresses[i]);
}
}
}
/**
* Approve transfer of all available tokens
* @param _token token address
*/
function approveAll(address _token) public {
address cToken = globalConfig.tokenInfoRegistry().getCToken(_token);
require(cToken != address(0x0), "cToken address is zero");
IERC20(_token).safeApprove(cToken, 0);
IERC20(_token).safeApprove(cToken, uint256(-1));
}
/**
* Get current block number
* @return the current block number
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* Transfer the token between users inside DeFiner
* @param _to the address that the token be transfered to
* @param _token token address
* @param _amount amout of tokens transfer
*/
function transfer(address _to, address _token, uint _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant {
globalConfig.bank().newRateIndexCheckpoint(_token);
uint256 amount = globalConfig.accounts().withdraw(msg.sender, _token, _amount);
globalConfig.accounts().deposit(_to, _token, amount);
emit Transfer(_token, msg.sender, _to, amount);
}
/**
* Borrow the amount of token from the saving pool.
* @param _token token address
* @param _amount amout of tokens to borrow
*/
function borrow(address _token, uint256 _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant {
require(_amount != 0, "Borrow zero amount of token is not allowed.");
globalConfig.bank().borrow(msg.sender, _token, _amount);
// Transfer the token on Ethereum
SavingLib.send(globalConfig, _amount, _token);
emit Borrow(_token, msg.sender, _amount);
}
/**
* Repay the amount of token back to the saving pool.
* @param _token token address
* @param _amount amout of tokens to borrow
* @dev If the repay amount is larger than the borrowed balance, the extra will be returned.
*/
function repay(address _token, uint256 _amount) public payable onlySupportedToken(_token) nonReentrant {
require(_amount != 0, "Amount is zero");
SavingLib.receive(globalConfig, _amount, _token);
// Add a new checkpoint on the index curve.
uint256 amount = globalConfig.bank().repay(msg.sender, _token, _amount);
// Send the remain money back
if(amount < _amount) {
SavingLib.send(globalConfig, _amount.sub(amount), _token);
}
emit Repay(_token, msg.sender, amount);
}
/**
* Deposit the amount of token to the saving pool.
* @param _token the address of the deposited token
* @param _amount the mount of the deposited token
*/
function deposit(address _token, uint256 _amount) public payable onlySupportedToken(_token) onlyEnabledToken(_token) nonReentrant {
require(_amount != 0, "Amount is zero");
SavingLib.receive(globalConfig, _amount, _token);
globalConfig.bank().deposit(msg.sender, _token, _amount);
emit Deposit(_token, msg.sender, _amount);
}
/**
* Withdraw a token from an address
* @param _token token address
* @param _amount amount to be withdrawn
*/
function withdraw(address _token, uint256 _amount) external onlySupportedToken(_token) whenNotPaused nonReentrant {
require(_amount != 0, "Amount is zero");
uint256 amount = globalConfig.bank().withdraw(msg.sender, _token, _amount);
SavingLib.send(globalConfig, amount, _token);
emit Withdraw(_token, msg.sender, amount);
}
/**
* Withdraw all tokens from the saving pool.
* @param _token the address of the withdrawn token
*/
function withdrawAll(address _token) external onlySupportedToken(_token) whenNotPaused nonReentrant {
// Sanity check
require(globalConfig.accounts().getDepositPrincipal(msg.sender, _token) > 0, "Token depositPrincipal must be greater than 0");
// Add a new checkpoint on the index curve.
globalConfig.bank().newRateIndexCheckpoint(_token);
// Get the total amount of token for the account
uint amount = globalConfig.accounts().getDepositBalanceCurrent(_token, msg.sender);
uint256 actualAmount = globalConfig.bank().withdraw(msg.sender, _token, amount);
if(actualAmount != 0) {
SavingLib.send(globalConfig, actualAmount, _token);
}
emit WithdrawAll(_token, msg.sender, actualAmount);
}
function liquidate(address _borrower, address _borrowedToken, address _collateralToken) public onlySupportedToken(_borrowedToken) onlySupportedToken(_collateralToken) whenNotPaused nonReentrant {
(uint256 repayAmount, uint256 payAmount) = globalConfig.accounts().liquidate(msg.sender, _borrower, _borrowedToken, _collateralToken);
emit Liquidate(msg.sender, _borrower, _borrowedToken, repayAmount, _collateralToken, payAmount);
}
/**
* Withdraw token from Compound
* @param _token token address
* @param _amount amount of token
*/
function fromCompound(address _token, uint _amount) external onlyAuthorized {
require(ICToken(globalConfig.tokenInfoRegistry().getCToken(_token)).redeemUnderlying(_amount) == 0, "redeemUnderlying failed");
}
function toCompound(address _token, uint _amount) external onlyAuthorized {
address cToken = globalConfig.tokenInfoRegistry().getCToken(_token);
if (Utils._isETH(address(globalConfig), _token)) {
ICETH(cToken).mint.value(_amount)();
} else {
// uint256 success = ICToken(cToken).mint(_amount);
require(ICToken(cToken).mint(_amount) == 0, "mint failed");
}
}
function() external payable{}
/**
* An account claim all mined FIN token
*/
function claim() public nonReentrant returns (uint256) {
uint256 finAmount = globalConfig.accounts().claim(msg.sender);
IERC20(FIN_ADDR).safeTransfer(msg.sender, finAmount);
emit Claim(msg.sender, finAmount);
return finAmount;
}
function claimForToken(address _token) public nonReentrant returns (uint256) {
uint256 finAmount = globalConfig.accounts().claimForToken(msg.sender, _token);
if(finAmount > 0) IERC20(FIN_ADDR).safeTransfer(msg.sender, finAmount);
emit Claim(msg.sender, finAmount);
return finAmount;
}
/**
* Withdraw COMP token to beneficiary
*/
/*
function withdrawCOMP(address _beneficiary) external onlyOwner {
uint256 compBalance = IERC20(COMP_ADDR).balanceOf(address(this));
IERC20(COMP_ADDR).safeTransfer(_beneficiary, compBalance);
emit WithdrawCOMP(_beneficiary, compBalance);
}
*/
function version() public pure returns(string memory) {
return "v1.2.0";
}
}
interface IGlobalConfig {
function savingAccount() external view returns (address);
function tokenInfoRegistry() external view returns (TokenRegistry);
function bank() external view returns (Bank);
function deFinerCommunityFund() external view returns (address);
function deFinerRate() external view returns (uint256);
function liquidationThreshold() external view returns (uint256);
function liquidationDiscountRatio() external view returns (uint256);
}
contract Accounts is Constant, Initializable{
using AccountTokenLib for AccountTokenLib.TokenInfo;
using BitmapLib for uint128;
using SafeMath for uint256;
using Math for uint256;
mapping(address => Account) public accounts;
IGlobalConfig globalConfig;
mapping(address => uint256) public FINAmount;
modifier onlyAuthorized() {
_isAuthorized();
_;
}
struct Account {
// Note, it's best practice to use functions minusAmount, addAmount, totalAmount
// to operate tokenInfos instead of changing it directly.
mapping(address => AccountTokenLib.TokenInfo) tokenInfos;
uint128 depositBitmap;
uint128 borrowBitmap;
uint128 collateralBitmap;
bool isCollInit;
}
event CollateralFlagChanged(address indexed _account, uint8 _index, bool _enabled);
function _isAuthorized() internal view {
require(
msg.sender == address(globalConfig.savingAccount()) || msg.sender == address(globalConfig.bank()),
"not authorized"
);
}
/**
* Initialize the Accounts
* @param _globalConfig the global configuration contract
*/
function initialize(
IGlobalConfig _globalConfig
) public initializer {
globalConfig = _globalConfig;
}
/**
* @dev Initialize the Collateral flag Bitmap for given account
* @notice This function is required for the contract upgrade, as previous users didn't
* have this collateral feature. So need to init the collateralBitmap for each user.
* @param _account User account address
*/
function initCollateralFlag(address _account) public {
Account storage account = accounts[_account];
// For all users by default `isCollInit` will be `false`
if(account.isCollInit == false) {
// Two conditions:
// 1) An account has some position previous to this upgrade
// THEN: copy `depositBitmap` to `collateralBitmap`
// 2) A new account is setup after this upgrade
// THEN: `depositBitmap` will be zero for that user, so don't copy
// all deposited tokens be treated as collateral
if(account.depositBitmap > 0) account.collateralBitmap = account.depositBitmap;
account.isCollInit = true;
}
// when isCollInit == true, function will just return after if condition check
}
/**
* @dev Enable/Disable collateral for a given token
* @param _tokenIndex Index of the token
* @param _enable `true` to enable the collateral, `false` to disable
*/
function setCollateral(uint8 _tokenIndex, bool _enable) public {
address accountAddr = msg.sender;
initCollateralFlag(accountAddr);
Account storage account = accounts[accountAddr];
if(_enable) {
account.collateralBitmap = account.collateralBitmap.setBit(_tokenIndex);
// when set new collateral, no need to evaluate borrow power
} else {
account.collateralBitmap = account.collateralBitmap.unsetBit(_tokenIndex);
// when unset collateral, evaluate borrow power, only when user borrowed already
if(account.borrowBitmap > 0) {
require(getBorrowETH(accountAddr) <= getBorrowPower(accountAddr), "Insufficient collateral");
}
}
emit CollateralFlagChanged(msg.sender, _tokenIndex, _enable);
}
function setCollateral(uint8[] calldata _tokenIndexArr, bool[] calldata _enableArr) external {
require(_tokenIndexArr.length == _enableArr.length, "array length does not match");
for(uint i = 0; i < _tokenIndexArr.length; i++) {
setCollateral(_tokenIndexArr[i], _enableArr[i]);
}
}
function getCollateralStatus(address _account)
external
view
returns (address[] memory tokens, bool[] memory status)
{
Account memory account = accounts[_account];
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
tokens = tokenRegistry.getTokens();
uint256 tokensCount = tokens.length;
status = new bool[](tokensCount);
uint128 collBitmap = account.collateralBitmap;
for(uint i = 0; i < tokensCount; i++) {
// Example: 0001 << 1 => 0010 (mask for 2nd position)
uint128 mask = uint128(1) << uint128(i);
bool isEnabled = (collBitmap & mask) > 0;
if(isEnabled) status[i] = true;
}
}
/**
* Check if the user has deposit for any tokens
* @param _account address of the user
* @return true if the user has positive deposit balance
*/
function isUserHasAnyDeposits(address _account) public view returns (bool) {
Account storage account = accounts[_account];
return account.depositBitmap > 0;
}
/**
* Check if the user has deposit for a token
* @param _account address of the user
* @param _index index of the token
* @return true if the user has positive deposit balance for the token
*/
function isUserHasDeposits(address _account, uint8 _index) public view returns (bool) {
Account storage account = accounts[_account];
return account.depositBitmap.isBitSet(_index);
}
/**
* Check if the user has borrowed a token
* @param _account address of the user
* @param _index index of the token
* @return true if the user has borrowed the token
*/
function isUserHasBorrows(address _account, uint8 _index) public view returns (bool) {
Account storage account = accounts[_account];
return account.borrowBitmap.isBitSet(_index);
}
/**
* Check if the user has collateral flag set
* @param _account address of the user
* @param _index index of the token
* @return true if the user has collateral flag set for the given index
*/
function isUserHasCollateral(address _account, uint8 _index) public view returns(bool) {
Account storage account = accounts[_account];
return account.collateralBitmap.isBitSet(_index);
}
/**
* Set the deposit bitmap for a token.
* @param _account address of the user
* @param _index index of the token
*/
function setInDepositBitmap(address _account, uint8 _index) internal {
Account storage account = accounts[_account];
account.depositBitmap = account.depositBitmap.setBit(_index);
}
/**
* Unset the deposit bitmap for a token
* @param _account address of the user
* @param _index index of the token
*/
function unsetFromDepositBitmap(address _account, uint8 _index) internal {
Account storage account = accounts[_account];
account.depositBitmap = account.depositBitmap.unsetBit(_index);
}
/**
* Set the borrow bitmap for a token.
* @param _account address of the user
* @param _index index of the token
*/
function setInBorrowBitmap(address _account, uint8 _index) internal {
Account storage account = accounts[_account];
account.borrowBitmap = account.borrowBitmap.setBit(_index);
}
/**
* Unset the borrow bitmap for a token
* @param _account address of the user
* @param _index index of the token
*/
function unsetFromBorrowBitmap(address _account, uint8 _index) internal {
Account storage account = accounts[_account];
account.borrowBitmap = account.borrowBitmap.unsetBit(_index);
}
function getDepositPrincipal(address _accountAddr, address _token) public view returns(uint256) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
return tokenInfo.getDepositPrincipal();
}
function getBorrowPrincipal(address _accountAddr, address _token) public view returns(uint256) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
return tokenInfo.getBorrowPrincipal();
}
function getLastDepositBlock(address _accountAddr, address _token) public view returns(uint256) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
return tokenInfo.getLastDepositBlock();
}
function getLastBorrowBlock(address _accountAddr, address _token) public view returns(uint256) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
return tokenInfo.getLastBorrowBlock();
}
/**
* Get deposit interest of an account for a specific token
* @param _account account address
* @param _token token address
* @dev The deposit interest may not have been updated in AccountTokenLib, so we need to explicited calcuate it.
*/
function getDepositInterest(address _account, address _token) public view returns(uint256) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token];
// If the account has never deposited the token, return 0.
uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();
if (lastDepositBlock == 0)
return 0;
else {
// As the last deposit block exists, the block is also a check point on index curve.
uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock);
return tokenInfo.calculateDepositInterest(accruedRate);
}
}
function getBorrowInterest(address _accountAddr, address _token) public view returns(uint256) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
// If the account has never borrowed the token, return 0
uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock();
if (lastBorrowBlock == 0)
return 0;
else {
// As the last borrow block exists, the block is also a check point on index curve.
uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, lastBorrowBlock);
return tokenInfo.calculateBorrowInterest(accruedRate);
}
}
function borrow(address _accountAddr, address _token, uint256 _amount) external onlyAuthorized {
initCollateralFlag(_accountAddr);
require(_amount != 0, "borrow amount is 0");
require(isUserHasAnyDeposits(_accountAddr), "no user deposits");
(uint8 tokenIndex, uint256 tokenDivisor, uint256 tokenPrice,) = globalConfig.tokenInfoRegistry().getTokenInfoFromAddress(_token);
require(
getBorrowETH(_accountAddr).add(_amount.mul(tokenPrice).div(tokenDivisor)) <=
getBorrowPower(_accountAddr), "Insufficient collateral when borrow"
);
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
uint256 blockNumber = getBlockNumber();
uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock();
if(lastBorrowBlock == 0)
tokenInfo.borrow(_amount, INT_UNIT, blockNumber);
else {
calculateBorrowFIN(lastBorrowBlock, _token, _accountAddr, blockNumber);
uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, lastBorrowBlock);
// Update the token principla and interest
tokenInfo.borrow(_amount, accruedRate, blockNumber);
}
// Since we have checked that borrow amount is larget than zero. We can set the borrow
// map directly without checking the borrow balance.
setInBorrowBitmap(_accountAddr, tokenIndex);
}
/**
* Update token info for withdraw. The interest will be withdrawn with higher priority.
*/
function withdraw(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized returns (uint256) {
initCollateralFlag(_accountAddr);
(, uint256 tokenDivisor, uint256 tokenPrice, uint256 borrowLTV) = globalConfig.tokenInfoRegistry().getTokenInfoFromAddress(_token);
// if user borrowed before then only check for under liquidation
Account memory account = accounts[_accountAddr];
if(account.borrowBitmap > 0) {
uint256 withdrawETH = _amount.mul(tokenPrice).mul(borrowLTV).div(tokenDivisor).div(100);
require(getBorrowETH(_accountAddr) <= getBorrowPower(_accountAddr).sub(withdrawETH), "Insufficient collateral");
}
(uint256 amountAfterCommission, ) = _withdraw(_accountAddr, _token, _amount, true);
return amountAfterCommission;
}
/**
* This function is called in liquidation function. There two difference between this function and
* the Account.withdraw function: 1) It doesn't check the user's borrow power, because the user
* is already borrowed more than it's borrowing power. 2) It doesn't take commissions.
*/
function withdraw_liquidate(address _accountAddr, address _token, uint256 _amount) internal {
_withdraw(_accountAddr, _token, _amount, false);
}
function _withdraw(address _accountAddr, address _token, uint256 _amount, bool _isCommission) internal returns (uint256, uint256) {
uint256 calcAmount = _amount;
// Check if withdraw amount is less than user's balance
require(calcAmount <= getDepositBalanceCurrent(_token, _accountAddr), "Insufficient balance");
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
uint256 lastBlock = tokenInfo.getLastDepositBlock();
uint256 blockNumber = getBlockNumber();
calculateDepositFIN(lastBlock, _token, _accountAddr, blockNumber);
uint256 principalBeforeWithdraw = tokenInfo.getDepositPrincipal();
if (lastBlock == 0)
tokenInfo.withdraw(calcAmount, INT_UNIT, blockNumber);
else {
// As the last deposit block exists, the block is also a check point on index curve.
uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastBlock);
tokenInfo.withdraw(calcAmount, accruedRate, blockNumber);
}
uint256 principalAfterWithdraw = tokenInfo.getDepositPrincipal();
if(principalAfterWithdraw == 0) {
uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token);
unsetFromDepositBitmap(_accountAddr, tokenIndex);
}
uint256 commission = 0;
if (_isCommission && _accountAddr != globalConfig.deFinerCommunityFund()) {
// DeFiner takes 10% commission on the interest a user earn
commission = calcAmount.sub(principalBeforeWithdraw.sub(principalAfterWithdraw)).mul(globalConfig.deFinerRate()).div(100);
deposit(globalConfig.deFinerCommunityFund(), _token, commission);
calcAmount = calcAmount.sub(commission);
}
return (calcAmount, commission);
}
/**
* Update token info for deposit
*/
function deposit(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized {
initCollateralFlag(_accountAddr);
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
if(tokenInfo.getDepositPrincipal() == 0) {
uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token);
setInDepositBitmap(_accountAddr, tokenIndex);
}
uint256 blockNumber = getBlockNumber();
uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();
if(lastDepositBlock == 0)
tokenInfo.deposit(_amount, INT_UNIT, blockNumber);
else {
calculateDepositFIN(lastDepositBlock, _token, _accountAddr, blockNumber);
uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock);
tokenInfo.deposit(_amount, accruedRate, blockNumber);
}
}
function repay(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized returns(uint256){
initCollateralFlag(_accountAddr);
// Update tokenInfo
uint256 amountOwedWithInterest = getBorrowBalanceCurrent(_token, _accountAddr);
uint256 amount = _amount > amountOwedWithInterest ? amountOwedWithInterest : _amount;
uint256 remain = _amount > amountOwedWithInterest ? _amount.sub(amountOwedWithInterest) : 0;
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
// Sanity check
uint256 borrowPrincipal = tokenInfo.getBorrowPrincipal();
uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock();
require(borrowPrincipal > 0, "BorrowPrincipal not gt 0");
if(lastBorrowBlock == 0)
tokenInfo.repay(amount, INT_UNIT, getBlockNumber());
else {
calculateBorrowFIN(lastBorrowBlock, _token, _accountAddr, getBlockNumber());
uint256 accruedRate = globalConfig.bank().getBorrowAccruedRate(_token, lastBorrowBlock);
tokenInfo.repay(amount, accruedRate, getBlockNumber());
}
if(borrowPrincipal == 0) {
uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token);
unsetFromBorrowBitmap(_accountAddr, tokenIndex);
}
return remain;
}
function getDepositBalanceCurrent(
address _token,
address _accountAddr
) public view returns (uint256 depositBalance) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
Bank bank = globalConfig.bank();
uint256 accruedRate;
uint256 depositRateIndex = bank.depositeRateIndex(_token, tokenInfo.getLastDepositBlock());
if(tokenInfo.getDepositPrincipal() == 0) {
return 0;
} else {
if(depositRateIndex == 0) {
accruedRate = INT_UNIT;
} else {
accruedRate = bank.depositeRateIndexNow(_token)
.mul(INT_UNIT)
.div(depositRateIndex);
}
return tokenInfo.getDepositBalance(accruedRate);
}
}
/**
* Get current borrow balance of a token
* @param _token token address
* @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance.
*/
function getBorrowBalanceCurrent(
address _token,
address _accountAddr
) public view returns (uint256 borrowBalance) {
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];
Bank bank = globalConfig.bank();
uint256 accruedRate;
uint256 borrowRateIndex = bank.borrowRateIndex(_token, tokenInfo.getLastBorrowBlock());
if(tokenInfo.getBorrowPrincipal() == 0) {
return 0;
} else {
if(borrowRateIndex == 0) {
accruedRate = INT_UNIT;
} else {
accruedRate = bank.borrowRateIndexNow(_token)
.mul(INT_UNIT)
.div(borrowRateIndex);
}
return tokenInfo.getBorrowBalance(accruedRate);
}
}
/**
* Calculate an account's borrow power based on token's LTV
*/
/*
function getBorrowPower(address _borrower) public view returns (uint256 power) {
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
uint256 tokenNum = tokenRegistry.getCoinLength();
for(uint256 i = 0; i < tokenNum; i++) {
if (isUserHasDeposits(_borrower, uint8(i))) {
(address token, uint256 divisor, uint256 price, uint256 borrowLTV) = tokenRegistry.getTokenInfoFromIndex(i);
uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _borrower);
power = power.add(depositBalanceCurrent.mul(price).mul(borrowLTV).div(100).div(divisor));
}
}
return power;
}
*/
function getBorrowPower(address _borrower) public view returns (uint256 power) {
Account storage account = accounts[_borrower];
// if a user have deposits in some tokens and collateral enabled for some
// then we need to iterate over his deposits for which collateral is also enabled.
// Hence, we can derive this information by perorming AND bitmap operation
// hasCollnDepositBitmap = collateralEnabled & hasDeposit
// Example:
// collateralBitmap = 0101
// depositBitmap = 0110
// ================================== OP AND
// hasCollnDepositBitmap = 0100 (user can only use his 3rd token as borrow power)
uint128 hasCollnDepositBitmap = account.collateralBitmap & account.depositBitmap;
// When no-collateral enabled and no-deposits just return '0' power
if(hasCollnDepositBitmap == 0) return power;
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
// This loop has max "O(n)" complexity where "n = TokensLength", but the loop
// calculates borrow power only for the `hasCollnDepositBitmap` bit, hence the loop
// iterates only till the highest bit set. Example 00000100, the loop will iterate
// only for 4 times, and only 1 time to calculate borrow the power.
// NOTE: When transaction gas-cost goes above the block gas limit, a user can
// disable some of his collaterals so that he can perform the borrow.
// Earlier loop implementation was iterating over all tokens, hence the platform
// were not able to add new tokens
for(uint i = 0; i < 128; i++) {
// if hasCollnDepositBitmap = 0000 then break the loop
if(hasCollnDepositBitmap > 0) {
// hasCollnDepositBitmap = 0100
// mask = 0001
// =============================== OP AND
// result = 0000
bool isEnabled = (hasCollnDepositBitmap & uint128(1)) > 0;
// Is i(th) token enabled?
if(isEnabled) {
// continue calculating borrow power for i(th) token
(address token, uint256 divisor, uint256 price, uint256 borrowLTV) = tokenRegistry.getTokenInfoFromIndex(i);
// avoid some gas consumption when borrowLTV == 0
if(borrowLTV != 0) {
uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _borrower);
power = power.add(depositBalanceCurrent.mul(price).mul(borrowLTV).div(100).div(divisor));
}
}
// right shift by 1
// hasCollnDepositBitmap = 0100
// BITWISE RIGHTSHIFT 1 on hasCollnDepositBitmap = 0010
hasCollnDepositBitmap = hasCollnDepositBitmap >> 1;
// continue loop and repeat the steps until `hasCollnDepositBitmap == 0`
} else {
break;
}
}
return power;
}
function getCollateralETH(address _account) public view returns (uint256 collETH) {
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
Account memory account = accounts[_account];
uint128 hasDeposits = account.depositBitmap;
for(uint8 i = 0; i < 128; i++) {
if(hasDeposits > 0) {
bool isEnabled = (hasDeposits & uint128(1)) > 0;
if(isEnabled) {
(address token,
uint256 divisor,
uint256 price,
uint256 borrowLTV) = tokenRegistry.getTokenInfoFromIndex(i);
if(borrowLTV != 0) {
uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _account);
collETH = collETH.add(depositBalanceCurrent.mul(price).div(divisor));
}
}
hasDeposits = hasDeposits >> 1;
} else {
break;
}
}
return collETH;
}
/**
* Get current deposit balance of a token
* @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance.
*/
function getDepositETH(
address _accountAddr
) public view returns (uint256 depositETH) {
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
Account memory account = accounts[_accountAddr];
uint128 hasDeposits = account.depositBitmap;
for(uint8 i = 0; i < 128; i++) {
if(hasDeposits > 0) {
bool isEnabled = (hasDeposits & uint128(1)) > 0;
if(isEnabled) {
(address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i);
uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _accountAddr);
depositETH = depositETH.add(depositBalanceCurrent.mul(price).div(divisor));
}
hasDeposits = hasDeposits >> 1;
} else {
break;
}
}
return depositETH;
}
/**
* Get borrowed balance of a token in the uint256 of Wei
*/
function getBorrowETH(
address _accountAddr
) public view returns (uint256 borrowETH) {
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
Account memory account = accounts[_accountAddr];
uint128 hasBorrows = account.borrowBitmap;
for(uint8 i = 0; i < 128; i++) {
if(hasBorrows > 0) {
bool isEnabled = (hasBorrows & uint128(1)) > 0;
if(isEnabled) {
(address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i);
uint256 borrowBalanceCurrent = getBorrowBalanceCurrent(token, _accountAddr);
borrowETH = borrowETH.add(borrowBalanceCurrent.mul(price).div(divisor));
}
hasBorrows = hasBorrows >> 1;
} else {
break;
}
}
return borrowETH;
}
/**
* Check if the account is liquidatable
* @param _borrower borrower's account
* @return true if the account is liquidatable
*/
function isAccountLiquidatable(address _borrower) public returns (bool) {
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
Bank bank = globalConfig.bank();
// Add new rate check points for all the collateral tokens from borrower in order to
// have accurate calculation of liquidation oppotunites.
Account memory account = accounts[_borrower];
uint128 hasBorrowsOrDeposits = account.borrowBitmap | account.depositBitmap;
for(uint8 i = 0; i < 128; i++) {
if(hasBorrowsOrDeposits > 0) {
bool isEnabled = (hasBorrowsOrDeposits & uint128(1)) > 0;
if(isEnabled) {
address token = tokenRegistry.addressFromIndex(i);
bank.newRateIndexCheckpoint(token);
}
hasBorrowsOrDeposits = hasBorrowsOrDeposits >> 1;
} else {
break;
}
}
uint256 liquidationThreshold = globalConfig.liquidationThreshold();
uint256 totalBorrow = getBorrowETH(_borrower);
uint256 totalCollateral = getCollateralETH(_borrower);
// It is required that LTV is larger than LIQUIDATE_THREADHOLD for liquidation
// return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold);
return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold);
}
struct LiquidationVars {
uint256 borrowerCollateralValue;
uint256 targetTokenBalance;
uint256 targetTokenBalanceBorrowed;
uint256 targetTokenPrice;
uint256 liquidationDiscountRatio;
uint256 totalBorrow;
uint256 borrowPower;
uint256 liquidateTokenBalance;
uint256 liquidateTokenPrice;
uint256 limitRepaymentValue;
uint256 borrowTokenLTV;
uint256 repayAmount;
uint256 payAmount;
}
function liquidate(
address _liquidator,
address _borrower,
address _borrowedToken,
address _collateralToken
)
external
onlyAuthorized
returns (
uint256,
uint256
)
{
initCollateralFlag(_liquidator);
initCollateralFlag(_borrower);
require(isAccountLiquidatable(_borrower), "borrower is not liquidatable");
// It is required that the liquidator doesn't exceed it's borrow power.
// if liquidator has any borrows, then only check for borrowPower condition
Account memory liquidateAcc = accounts[_liquidator];
if(liquidateAcc.borrowBitmap > 0) {
require(
getBorrowETH(_liquidator) < getBorrowPower(_liquidator),
"No extra funds used for liquidation"
);
}
LiquidationVars memory vars;
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
// _borrowedToken balance of the liquidator (deposit balance)
vars.targetTokenBalance = getDepositBalanceCurrent(_borrowedToken, _liquidator);
require(vars.targetTokenBalance > 0, "amount must be > 0");
// _borrowedToken balance of the borrower (borrow balance)
vars.targetTokenBalanceBorrowed = getBorrowBalanceCurrent(_borrowedToken, _borrower);
require(vars.targetTokenBalanceBorrowed > 0, "borrower not own any debt token");
// _borrowedToken available for liquidation
uint256 borrowedTokenAmountForLiquidation = vars.targetTokenBalance.min(vars.targetTokenBalanceBorrowed);
// _collateralToken balance of the borrower (deposit balance)
vars.liquidateTokenBalance = getDepositBalanceCurrent(_collateralToken, _borrower);
uint256 targetTokenDivisor;
(
,
targetTokenDivisor,
vars.targetTokenPrice,
vars.borrowTokenLTV
) = tokenRegistry.getTokenInfoFromAddress(_borrowedToken);
uint256 liquidateTokendivisor;
uint256 collateralLTV;
(
,
liquidateTokendivisor,
vars.liquidateTokenPrice,
collateralLTV
) = tokenRegistry.getTokenInfoFromAddress(_collateralToken);
// _collateralToken to purchase so that borrower's balance matches its borrow power
vars.totalBorrow = getBorrowETH(_borrower);
vars.borrowPower = getBorrowPower(_borrower);
vars.liquidationDiscountRatio = globalConfig.liquidationDiscountRatio();
vars.limitRepaymentValue = vars.totalBorrow.sub(vars.borrowPower)
.mul(100)
.div(vars.liquidationDiscountRatio.sub(collateralLTV));
uint256 collateralTokenValueForLiquidation = vars.limitRepaymentValue.min(
vars.liquidateTokenBalance
.mul(vars.liquidateTokenPrice)
.div(liquidateTokendivisor)
);
uint256 liquidationValue = collateralTokenValueForLiquidation.min(
borrowedTokenAmountForLiquidation
.mul(vars.targetTokenPrice)
.mul(100)
.div(targetTokenDivisor)
.div(vars.liquidationDiscountRatio)
);
vars.repayAmount = liquidationValue.mul(vars.liquidationDiscountRatio)
.mul(targetTokenDivisor)
.div(100)
.div(vars.targetTokenPrice);
vars.payAmount = vars.repayAmount.mul(liquidateTokendivisor)
.mul(100)
.mul(vars.targetTokenPrice);
vars.payAmount = vars.payAmount.div(targetTokenDivisor)
.div(vars.liquidationDiscountRatio)
.div(vars.liquidateTokenPrice);
deposit(_liquidator, _collateralToken, vars.payAmount);
withdraw_liquidate(_liquidator, _borrowedToken, vars.repayAmount);
withdraw_liquidate(_borrower, _collateralToken, vars.payAmount);
repay(_borrower, _borrowedToken, vars.repayAmount);
return (vars.repayAmount, vars.payAmount);
}
/**
* Get current block number
* @return the current block number
*/
function getBlockNumber() private view returns (uint256) {
return block.number;
}
/**
* An account claim all mined FIN token.
* @dev If the FIN mining index point doesn't exist, we have to calculate the FIN amount
* accurately. So the user can withdraw all available FIN tokens.
*/
function claim(address _account) public onlyAuthorized returns(uint256){
TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();
Bank bank = globalConfig.bank();
uint256 currentBlock = getBlockNumber();
Account memory account = accounts[_account];
uint128 depositBitmap = account.depositBitmap;
uint128 borrowBitmap = account.borrowBitmap;
uint128 hasDepositOrBorrow = depositBitmap | borrowBitmap;
for(uint8 i = 0; i < 128; i++) {
if(hasDepositOrBorrow > 0) {
if((hasDepositOrBorrow & uint128(1)) > 0) {
address token = tokenRegistry.addressFromIndex(i);
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[token];
bank.updateMining(token);
if (depositBitmap.isBitSet(i)) {
bank.updateDepositFINIndex(token);
uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();
calculateDepositFIN(lastDepositBlock, token, _account, currentBlock);
tokenInfo.deposit(0, bank.getDepositAccruedRate(token, lastDepositBlock), currentBlock);
}
if (borrowBitmap.isBitSet(i)) {
bank.updateBorrowFINIndex(token);
uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock();
calculateBorrowFIN(lastBorrowBlock, token, _account, currentBlock);
tokenInfo.borrow(0, bank.getBorrowAccruedRate(token, lastBorrowBlock), currentBlock);
}
}
hasDepositOrBorrow = hasDepositOrBorrow >> 1;
} else {
break;
}
}
uint256 _FINAmount = FINAmount[_account];
FINAmount[_account] = 0;
return _FINAmount;
}
function claimForToken(address _account, address _token) public onlyAuthorized returns(uint256) {
Account memory account = accounts[_account];
uint8 index = globalConfig.tokenInfoRegistry().getTokenIndex(_token);
bool isDeposit = account.depositBitmap.isBitSet(index);
bool isBorrow = account.borrowBitmap.isBitSet(index);
if(! (isDeposit || isBorrow)) return 0;
Bank bank = globalConfig.bank();
uint256 currentBlock = getBlockNumber();
AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token];
bank.updateMining(_token);
if (isDeposit) {
bank.updateDepositFINIndex(_token);
uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();
calculateDepositFIN(lastDepositBlock, _token, _account, currentBlock);
tokenInfo.deposit(0, bank.getDepositAccruedRate(_token, lastDepositBlock), currentBlock);
}
if (isBorrow) {
bank.updateBorrowFINIndex(_token);
uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock();
calculateBorrowFIN(lastBorrowBlock, _token, _account, currentBlock);
tokenInfo.borrow(0, bank.getBorrowAccruedRate(_token, lastBorrowBlock), currentBlock);
}
uint256 _FINAmount = FINAmount[_account];
FINAmount[_account] = 0;
return _FINAmount;
}
/**
* Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock
*/
function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal {
Bank bank = globalConfig.bank();
uint256 indexDifference = bank.depositFINRateIndex(_token, _currentBlock)
.sub(bank.depositFINRateIndex(_token, _lastBlock));
uint256 getFIN = getDepositBalanceCurrent(_token, _accountAddr)
.mul(indexDifference)
.div(bank.depositeRateIndex(_token, _currentBlock));
FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN);
}
/**
* Accumulate the amount FIN mined by borrowing between _lastBlock and _currentBlock
*/
function calculateBorrowFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal {
Bank bank = globalConfig.bank();
uint256 indexDifference = bank.borrowFINRateIndex(_token, _currentBlock)
.sub(bank.borrowFINRateIndex(_token, _lastBlock));
uint256 getFIN = getBorrowBalanceCurrent(_token, _accountAddr)
.mul(indexDifference)
.div(bank.borrowRateIndex(_token, _currentBlock));
FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN);
}
function version() public pure returns(string memory) {
return "v1.2.0";
}
}
contract GlobalConfig is Ownable {
using SafeMath for uint256;
uint256 public communityFundRatio = 20;
uint256 public minReserveRatio = 10;
uint256 public maxReserveRatio = 20;
uint256 public liquidationThreshold = 85;
uint256 public liquidationDiscountRatio = 95;
uint256 public compoundSupplyRateWeights = 1;
uint256 public compoundBorrowRateWeights = 9;
uint256 public rateCurveSlope = 0;
uint256 public rateCurveConstant = 4 * 10 ** 16;
uint256 public deFinerRate = 25;
address payable public deFinerCommunityFund = 0xC0fd76eDcb8893a83c293ed06a362b1c18a584C7;
Bank public bank; // the Bank contract
SavingAccount public savingAccount; // the SavingAccount contract
TokenRegistry public tokenInfoRegistry; // the TokenRegistry contract
Accounts public accounts; // the Accounts contract
Constant public constants; // the constants contract
event CommunityFundRatioUpdated(uint256 indexed communityFundRatio);
event MinReserveRatioUpdated(uint256 indexed minReserveRatio);
event MaxReserveRatioUpdated(uint256 indexed maxReserveRatio);
event LiquidationThresholdUpdated(uint256 indexed liquidationThreshold);
event LiquidationDiscountRatioUpdated(uint256 indexed liquidationDiscountRatio);
event CompoundSupplyRateWeightsUpdated(uint256 indexed compoundSupplyRateWeights);
event CompoundBorrowRateWeightsUpdated(uint256 indexed compoundBorrowRateWeights);
event rateCurveSlopeUpdated(uint256 indexed rateCurveSlope);
event rateCurveConstantUpdated(uint256 indexed rateCurveConstant);
event ConstantUpdated(address indexed constants);
event BankUpdated(address indexed bank);
event SavingAccountUpdated(address indexed savingAccount);
event TokenInfoRegistryUpdated(address indexed tokenInfoRegistry);
event AccountsUpdated(address indexed accounts);
event DeFinerCommunityFundUpdated(address indexed deFinerCommunityFund);
event DeFinerRateUpdated(uint256 indexed deFinerRate);
event ChainLinkUpdated(address indexed chainLink);
function initialize(
Bank _bank,
SavingAccount _savingAccount,
TokenRegistry _tokenInfoRegistry,
Accounts _accounts,
Constant _constants
) public onlyOwner {
bank = _bank;
savingAccount = _savingAccount;
tokenInfoRegistry = _tokenInfoRegistry;
accounts = _accounts;
constants = _constants;
}
/**
* Update the community fund (commision fee) ratio.
* @param _communityFundRatio the new ratio
*/
function updateCommunityFundRatio(uint256 _communityFundRatio) external onlyOwner {
if (_communityFundRatio == communityFundRatio)
return;
require(_communityFundRatio > 0 && _communityFundRatio < 100,
"Invalid community fund ratio.");
communityFundRatio = _communityFundRatio;
emit CommunityFundRatioUpdated(_communityFundRatio);
}
/**
* Update the minimum reservation reatio
* @param _minReserveRatio the new value of the minimum reservation ratio
*/
function updateMinReserveRatio(uint256 _minReserveRatio) external onlyOwner {
if (_minReserveRatio == minReserveRatio)
return;
require(_minReserveRatio > 0 && _minReserveRatio < maxReserveRatio,
"Invalid min reserve ratio.");
minReserveRatio = _minReserveRatio;
emit MinReserveRatioUpdated(_minReserveRatio);
}
/**
* Update the maximum reservation reatio
* @param _maxReserveRatio the new value of the maximum reservation ratio
*/
function updateMaxReserveRatio(uint256 _maxReserveRatio) external onlyOwner {
if (_maxReserveRatio == maxReserveRatio)
return;
require(_maxReserveRatio > minReserveRatio && _maxReserveRatio < 100,
"Invalid max reserve ratio.");
maxReserveRatio = _maxReserveRatio;
emit MaxReserveRatioUpdated(_maxReserveRatio);
}
/**
* Update the liquidation threshold, i.e. the LTV that will trigger the liquidation.
* @param _liquidationThreshold the new threshhold value
*/
function updateLiquidationThreshold(uint256 _liquidationThreshold) external onlyOwner {
if (_liquidationThreshold == liquidationThreshold)
return;
require(_liquidationThreshold > 0 && _liquidationThreshold < liquidationDiscountRatio,
"Invalid liquidation threshold.");
liquidationThreshold = _liquidationThreshold;
emit LiquidationThresholdUpdated(_liquidationThreshold);
}
/**
* Update the liquidation discount
* @param _liquidationDiscountRatio the new liquidation discount
*/
function updateLiquidationDiscountRatio(uint256 _liquidationDiscountRatio) external onlyOwner {
if (_liquidationDiscountRatio == liquidationDiscountRatio)
return;
require(_liquidationDiscountRatio > liquidationThreshold && _liquidationDiscountRatio < 100,
"Invalid liquidation discount ratio.");
liquidationDiscountRatio = _liquidationDiscountRatio;
emit LiquidationDiscountRatioUpdated(_liquidationDiscountRatio);
}
/**
* Medium value of the reservation ratio, which is the value that the pool try to maintain.
*/
function midReserveRatio() public view returns(uint256){
return minReserveRatio.add(maxReserveRatio).div(2);
}
function updateCompoundSupplyRateWeights(uint256 _compoundSupplyRateWeights) external onlyOwner{
compoundSupplyRateWeights = _compoundSupplyRateWeights;
emit CompoundSupplyRateWeightsUpdated(_compoundSupplyRateWeights);
}
function updateCompoundBorrowRateWeights(uint256 _compoundBorrowRateWeights) external onlyOwner{
compoundBorrowRateWeights = _compoundBorrowRateWeights;
emit CompoundBorrowRateWeightsUpdated(_compoundBorrowRateWeights);
}
function updaterateCurveSlope(uint256 _rateCurveSlope) external onlyOwner{
rateCurveSlope = _rateCurveSlope;
emit rateCurveSlopeUpdated(_rateCurveSlope);
}
function updaterateCurveConstant(uint256 _rateCurveConstant) external onlyOwner{
rateCurveConstant = _rateCurveConstant;
emit rateCurveConstantUpdated(_rateCurveConstant);
}
function updateBank(Bank _bank) external onlyOwner{
bank = _bank;
emit BankUpdated(address(_bank));
}
function updateSavingAccount(SavingAccount _savingAccount) external onlyOwner{
savingAccount = _savingAccount;
emit SavingAccountUpdated(address(_savingAccount));
}
function updateTokenInfoRegistry(TokenRegistry _tokenInfoRegistry) external onlyOwner{
tokenInfoRegistry = _tokenInfoRegistry;
emit TokenInfoRegistryUpdated(address(_tokenInfoRegistry));
}
function updateAccounts(Accounts _accounts) external onlyOwner{
accounts = _accounts;
emit AccountsUpdated(address(_accounts));
}
function updateConstant(Constant _constants) external onlyOwner{
constants = _constants;
emit ConstantUpdated(address(_constants));
}
function updatedeFinerCommunityFund(address payable _deFinerCommunityFund) external onlyOwner{
deFinerCommunityFund = _deFinerCommunityFund;
emit DeFinerCommunityFundUpdated(_deFinerCommunityFund);
}
function updatedeFinerRate(uint256 _deFinerRate) external onlyOwner{
require(_deFinerRate <= 100,"_deFinerRate cannot exceed 100");
deFinerRate = _deFinerRate;
emit DeFinerRateUpdated(_deFinerRate);
}
}
interface ICToken {
function supplyRatePerBlock() external view returns (uint);
function borrowRatePerBlock() external view returns (uint);
function mint(uint mintAmount) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function redeem(uint redeemAmount) external returns (uint);
function exchangeRateStore() external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint);
}
interface ICETH{
function mint() external payable;
}
interface IController {
function fastForward(uint blocks) external returns (uint);
function getBlockNumber() external view returns (uint);
}
contract Bank is Constant, Initializable{
using SafeMath for uint256;
mapping(address => uint256) public totalLoans; // amount of lended tokens
mapping(address => uint256) public totalReserve; // amount of tokens in reservation
mapping(address => uint256) public totalCompound; // amount of tokens in compound
// Token => block-num => rate
mapping(address => mapping(uint => uint)) public depositeRateIndex; // the index curve of deposit rate
// Token => block-num => rate
mapping(address => mapping(uint => uint)) public borrowRateIndex; // the index curve of borrow rate
// token address => block number
mapping(address => uint) public lastCheckpoint; // last checkpoint on the index curve
// cToken address => rate
mapping(address => uint) public lastCTokenExchangeRate; // last compound cToken exchange rate
mapping(address => ThirdPartyPool) compoundPool; // the compound pool
GlobalConfig globalConfig; // global configuration contract address
mapping(address => mapping(uint => uint)) public depositFINRateIndex;
mapping(address => mapping(uint => uint)) public borrowFINRateIndex;
mapping(address => uint) public lastDepositFINRateCheckpoint;
mapping(address => uint) public lastBorrowFINRateCheckpoint;
modifier onlyAuthorized() {
require(msg.sender == address(globalConfig.savingAccount()) || msg.sender == address(globalConfig.accounts()),
"Only authorized to call from DeFiner internal contracts.");
_;
}
struct ThirdPartyPool {
bool supported; // if the token is supported by the third party platforms such as Compound
uint capitalRatio; // the ratio of the capital in third party to the total asset
uint depositRatePerBlock; // the deposit rate of the token in third party
uint borrowRatePerBlock; // the borrow rate of the token in third party
}
event UpdateIndex(address indexed token, uint256 depositeRateIndex, uint256 borrowRateIndex);
event UpdateDepositFINIndex(address indexed _token, uint256 depositFINRateIndex);
event UpdateBorrowFINIndex(address indexed _token, uint256 borrowFINRateIndex);
/**
* Initialize the Bank
* @param _globalConfig the global configuration contract
*/
function initialize(
GlobalConfig _globalConfig
) public initializer {
globalConfig = _globalConfig;
}
/**
* Total amount of the token in Saving account
* @param _token token address
*/
function getTotalDepositStore(address _token) public view returns(uint) {
address cToken = globalConfig.tokenInfoRegistry().getCToken(_token);
// totalLoans[_token] = U totalReserve[_token] = R
return totalCompound[cToken].add(totalLoans[_token]).add(totalReserve[_token]); // return totalAmount = C + U + R
}
/**
* Update total amount of token in Compound as the cToken price changed
* @param _token token address
*/
function updateTotalCompound(address _token) internal {
address cToken = globalConfig.tokenInfoRegistry().getCToken(_token);
if(cToken != address(0)) {
totalCompound[cToken] = ICToken(cToken).balanceOfUnderlying(address(globalConfig.savingAccount()));
}
}
/**
* Update the total reservation. Before run this function, make sure that totalCompound has been updated
* by calling updateTotalCompound. Otherwise, totalCompound may not equal to the exact amount of the
* token in Compound.
* @param _token token address
* @param _action indicate if user's operation is deposit or withdraw, and borrow or repay.
* @return the actuall amount deposit/withdraw from the saving pool
*/
function updateTotalReserve(address _token, uint _amount, ActionType _action) internal returns(uint256 compoundAmount){
address cToken = globalConfig.tokenInfoRegistry().getCToken(_token);
uint totalAmount = getTotalDepositStore(_token);
if (_action == ActionType.DepositAction || _action == ActionType.RepayAction) {
// Total amount of token after deposit or repay
if (_action == ActionType.DepositAction)
totalAmount = totalAmount.add(_amount);
else
totalLoans[_token] = totalLoans[_token].sub(_amount);
// Expected total amount of token in reservation after deposit or repay
uint totalReserveBeforeAdjust = totalReserve[_token].add(_amount);
if (cToken != address(0) &&
totalReserveBeforeAdjust > totalAmount.mul(globalConfig.maxReserveRatio()).div(100)) {
uint toCompoundAmount = totalReserveBeforeAdjust.sub(totalAmount.mul(globalConfig.midReserveRatio()).div(100));
//toCompound(_token, toCompoundAmount);
compoundAmount = toCompoundAmount;
totalCompound[cToken] = totalCompound[cToken].add(toCompoundAmount);
totalReserve[_token] = totalReserve[_token].add(_amount).sub(toCompoundAmount);
}
else {
totalReserve[_token] = totalReserve[_token].add(_amount);
}
} else {
// The lack of liquidity exception happens when the pool doesn't have enough tokens for borrow/withdraw
// It happens when part of the token has lended to the other accounts.
// However in case of withdrawAll, even if the token has no loan, this requirment may still false because
// of the precision loss in the rate calcuation. So we put a logic here to deal with this case: in case
// of withdrawAll and there is no loans for the token, we just adjust the balance in bank contract to the
// to the balance of that individual account.
if(_action == ActionType.WithdrawAction) {
if(totalLoans[_token] != 0)
require(getPoolAmount(_token) >= _amount, "Lack of liquidity when withdraw.");
else if (getPoolAmount(_token) < _amount)
totalReserve[_token] = _amount.sub(totalCompound[cToken]);
totalAmount = getTotalDepositStore(_token);
}
else
require(getPoolAmount(_token) >= _amount, "Lack of liquidity when borrow.");
// Total amount of token after withdraw or borrow
if (_action == ActionType.WithdrawAction)
totalAmount = totalAmount.sub(_amount);
else
totalLoans[_token] = totalLoans[_token].add(_amount);
// Expected total amount of token in reservation after deposit or repay
uint totalReserveBeforeAdjust = totalReserve[_token] > _amount ? totalReserve[_token].sub(_amount) : 0;
// Trigger fromCompound if the new reservation ratio is less than 10%
if(cToken != address(0) &&
(totalAmount == 0 || totalReserveBeforeAdjust < totalAmount.mul(globalConfig.minReserveRatio()).div(100))) {
uint totalAvailable = totalReserve[_token].add(totalCompound[cToken]).sub(_amount);
if (totalAvailable < totalAmount.mul(globalConfig.midReserveRatio()).div(100)){
// Withdraw all the tokens from Compound
compoundAmount = totalCompound[cToken];
totalCompound[cToken] = 0;
totalReserve[_token] = totalAvailable;
} else {
// Withdraw partial tokens from Compound
uint totalInCompound = totalAvailable.sub(totalAmount.mul(globalConfig.midReserveRatio()).div(100));
compoundAmount = totalCompound[cToken].sub(totalInCompound);
totalCompound[cToken] = totalInCompound;
totalReserve[_token] = totalAvailable.sub(totalInCompound);
}
}
else {
totalReserve[_token] = totalReserve[_token].sub(_amount);
}
}
return compoundAmount;
}
function update(address _token, uint _amount, ActionType _action) public onlyAuthorized returns(uint256 compoundAmount) {
updateTotalCompound(_token);
// updateTotalLoan(_token);
compoundAmount = updateTotalReserve(_token, _amount, _action);
return compoundAmount;
}
/**
* The function is called in Bank.deposit(), Bank.withdraw() and Accounts.claim() functions.
* The function should be called AFTER the newRateIndexCheckpoint function so that the account balances are
* accurate, and BEFORE the account balance acutally updated due to deposit/withdraw activities.
*/
function updateDepositFINIndex(address _token) public onlyAuthorized{
uint currentBlock = getBlockNumber();
uint deltaBlock;
// If it is the first deposit FIN rate checkpoint, set the deltaBlock value be 0 so that the first
// point on depositFINRateIndex is zero.
deltaBlock = lastDepositFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastDepositFINRateCheckpoint[_token]);
// If the totalDeposit of the token is zero, no FIN token should be mined and the FINRateIndex is unchanged.
depositFINRateIndex[_token][currentBlock] = depositFINRateIndex[_token][lastDepositFINRateCheckpoint[_token]].add(
getTotalDepositStore(_token) == 0 ? 0 : depositeRateIndex[_token][lastCheckpoint[_token]]
.mul(deltaBlock)
.mul(globalConfig.tokenInfoRegistry().depositeMiningSpeeds(_token))
.div(getTotalDepositStore(_token)));
lastDepositFINRateCheckpoint[_token] = currentBlock;
emit UpdateDepositFINIndex(_token, depositFINRateIndex[_token][currentBlock]);
}
function updateBorrowFINIndex(address _token) public onlyAuthorized{
uint currentBlock = getBlockNumber();
uint deltaBlock;
// If it is the first borrow FIN rate checkpoint, set the deltaBlock value be 0 so that the first
// point on borrowFINRateIndex is zero.
deltaBlock = lastBorrowFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastBorrowFINRateCheckpoint[_token]);
// If the totalBorrow of the token is zero, no FIN token should be mined and the FINRateIndex is unchanged.
borrowFINRateIndex[_token][currentBlock] = borrowFINRateIndex[_token][lastBorrowFINRateCheckpoint[_token]].add(
totalLoans[_token] == 0 ? 0 : borrowRateIndex[_token][lastCheckpoint[_token]]
.mul(deltaBlock)
.mul(globalConfig.tokenInfoRegistry().borrowMiningSpeeds(_token))
.div(totalLoans[_token]));
lastBorrowFINRateCheckpoint[_token] = currentBlock;
emit UpdateBorrowFINIndex(_token, borrowFINRateIndex[_token][currentBlock]);
}
function updateMining(address _token) public onlyAuthorized{
newRateIndexCheckpoint(_token);
updateTotalCompound(_token);
}
/**
* Get the borrowing interest rate.
* @param _token token address
* @return the borrow rate for the current block
*/
function getBorrowRatePerBlock(address _token) public view returns(uint) {
uint256 capitalUtilizationRatio = getCapitalUtilizationRatio(_token);
// rateCurveConstant = <'3 * (10)^16'_rateCurveConstant_configurable>
uint256 rateCurveConstant = globalConfig.rateCurveConstant();
// compoundSupply = Compound Supply Rate * <'0.4'_supplyRateWeights_configurable>
uint256 compoundSupply = compoundPool[_token].depositRatePerBlock.mul(globalConfig.compoundSupplyRateWeights());
// compoundBorrow = Compound Borrow Rate * <'0.6'_borrowRateWeights_configurable>
uint256 compoundBorrow = compoundPool[_token].borrowRatePerBlock.mul(globalConfig.compoundBorrowRateWeights());
// nonUtilizedCapRatio = (1 - U) // Non utilized capital ratio
uint256 nonUtilizedCapRatio = INT_UNIT.sub(capitalUtilizationRatio);
bool isSupportedOnCompound = globalConfig.tokenInfoRegistry().isSupportedOnCompound(_token);
if(isSupportedOnCompound) {
uint256 compoundSupplyPlusBorrow = compoundSupply.add(compoundBorrow).div(10);
uint256 rateConstant;
// if the token is supported in third party (like Compound), check if U = 1
if(capitalUtilizationRatio > ((10**18) - (10**15))) { // > 0.999
// if U = 1, borrowing rate = compoundSupply + compoundBorrow + ((rateCurveConstant * 100) / BLOCKS_PER_YEAR)
rateConstant = rateCurveConstant.mul(1000).div(BLOCKS_PER_YEAR);
return compoundSupplyPlusBorrow.add(rateConstant);
} else {
// if U != 1, borrowing rate = compoundSupply + compoundBorrow + ((rateCurveConstant / (1 - U)) / BLOCKS_PER_YEAR)
rateConstant = rateCurveConstant.mul(10**18).div(nonUtilizedCapRatio).div(BLOCKS_PER_YEAR);
return compoundSupplyPlusBorrow.add(rateConstant);
}
} else {
// If the token is NOT supported by the third party, check if U = 1
if(capitalUtilizationRatio > ((10**18) - (10**15))) { // > 0.999
// if U = 1, borrowing rate = rateCurveConstant * 100
return rateCurveConstant.mul(1000).div(BLOCKS_PER_YEAR);
} else {
// if 0 < U < 1, borrowing rate = 3% / (1 - U)
return rateCurveConstant.mul(10**18).div(nonUtilizedCapRatio).div(BLOCKS_PER_YEAR);
}
}
}
/**
* Get Deposit Rate. Deposit APR = (Borrow APR * Utilization Rate (U) + Compound Supply Rate *
* Capital Compound Ratio (C) )* (1- DeFiner Community Fund Ratio (D)). The scaling is 10 ** 18
* @param _token token address
* @return deposite rate of blocks before the current block
*/
function getDepositRatePerBlock(address _token) public view returns(uint) {
uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token);
uint256 capitalUtilRatio = getCapitalUtilizationRatio(_token);
if(!globalConfig.tokenInfoRegistry().isSupportedOnCompound(_token))
return borrowRatePerBlock.mul(capitalUtilRatio).div(INT_UNIT);
return borrowRatePerBlock.mul(capitalUtilRatio).add(compoundPool[_token].depositRatePerBlock
.mul(compoundPool[_token].capitalRatio)).div(INT_UNIT);
}
/**
* Get capital utilization. Capital Utilization Rate (U )= total loan outstanding / Total market deposit
* @param _token token address
* @return Capital utilization ratio `U`.
* Valid range: 0 ≤ U ≤ 10^18
*/
function getCapitalUtilizationRatio(address _token) public view returns(uint) {
uint256 totalDepositsNow = getTotalDepositStore(_token);
if(totalDepositsNow == 0) {
return 0;
} else {
return totalLoans[_token].mul(INT_UNIT).div(totalDepositsNow);
}
}
/**
* Ratio of the capital in Compound
* @param _token token address
*/
function getCapitalCompoundRatio(address _token) public view returns(uint) {
address cToken = globalConfig.tokenInfoRegistry().getCToken(_token);
if(totalCompound[cToken] == 0 ) {
return 0;
} else {
return uint(totalCompound[cToken].mul(INT_UNIT).div(getTotalDepositStore(_token)));
}
}
/**
* It's a utility function. Get the cummulative deposit rate in a block interval ending in current block
* @param _token token address
* @param _depositRateRecordStart the start block of the interval
* @dev This function should always be called after current block is set as a new rateIndex point.
*/
function getDepositAccruedRate(address _token, uint _depositRateRecordStart) external view returns (uint256) {
uint256 depositRate = depositeRateIndex[_token][_depositRateRecordStart];
require(depositRate != 0, "_depositRateRecordStart is not a check point on index curve.");
return depositeRateIndexNow(_token).mul(INT_UNIT).div(depositRate);
}
/**
* Get the cummulative borrow rate in a block interval ending in current block
* @param _token token address
* @param _borrowRateRecordStart the start block of the interval
* @dev This function should always be called after current block is set as a new rateIndex point.
*/
function getBorrowAccruedRate(address _token, uint _borrowRateRecordStart) external view returns (uint256) {
uint256 borrowRate = borrowRateIndex[_token][_borrowRateRecordStart];
require(borrowRate != 0, "_borrowRateRecordStart is not a check point on index curve.");
return borrowRateIndexNow(_token).mul(INT_UNIT).div(borrowRate);
}
/**
* Set a new rate index checkpoint.
* @param _token token address
* @dev The rate set at the checkpoint is the rate from the last checkpoint to this checkpoint
*/
function newRateIndexCheckpoint(address _token) public onlyAuthorized {
// return if the rate check point already exists
uint blockNumber = getBlockNumber();
if (blockNumber == lastCheckpoint[_token])
return;
uint256 UNIT = INT_UNIT;
address cToken = globalConfig.tokenInfoRegistry().getCToken(_token);
// If it is the first check point, initialize the rate index
uint256 previousCheckpoint = lastCheckpoint[_token];
if (lastCheckpoint[_token] == 0) {
if(cToken == address(0)) {
compoundPool[_token].supported = false;
borrowRateIndex[_token][blockNumber] = UNIT;
depositeRateIndex[_token][blockNumber] = UNIT;
// Update the last checkpoint
lastCheckpoint[_token] = blockNumber;
}
else {
compoundPool[_token].supported = true;
uint cTokenExchangeRate = ICToken(cToken).exchangeRateCurrent();
// Get the curretn cToken exchange rate in Compound, which is need to calculate DeFiner's rate
compoundPool[_token].capitalRatio = getCapitalCompoundRatio(_token);
compoundPool[_token].borrowRatePerBlock = ICToken(cToken).borrowRatePerBlock(); // initial value
compoundPool[_token].depositRatePerBlock = ICToken(cToken).supplyRatePerBlock(); // initial value
borrowRateIndex[_token][blockNumber] = UNIT;
depositeRateIndex[_token][blockNumber] = UNIT;
// Update the last checkpoint
lastCheckpoint[_token] = blockNumber;
lastCTokenExchangeRate[cToken] = cTokenExchangeRate;
}
} else {
if(cToken == address(0)) {
compoundPool[_token].supported = false;
borrowRateIndex[_token][blockNumber] = borrowRateIndexNow(_token);
depositeRateIndex[_token][blockNumber] = depositeRateIndexNow(_token);
// Update the last checkpoint
lastCheckpoint[_token] = blockNumber;
} else {
compoundPool[_token].supported = true;
uint cTokenExchangeRate = ICToken(cToken).exchangeRateCurrent();
// Get the curretn cToken exchange rate in Compound, which is need to calculate DeFiner's rate
compoundPool[_token].capitalRatio = getCapitalCompoundRatio(_token);
compoundPool[_token].borrowRatePerBlock = ICToken(cToken).borrowRatePerBlock();
compoundPool[_token].depositRatePerBlock = cTokenExchangeRate.mul(UNIT).div(lastCTokenExchangeRate[cToken])
.sub(UNIT).div(blockNumber.sub(lastCheckpoint[_token]));
borrowRateIndex[_token][blockNumber] = borrowRateIndexNow(_token);
depositeRateIndex[_token][blockNumber] = depositeRateIndexNow(_token);
// Update the last checkpoint
lastCheckpoint[_token] = blockNumber;
lastCTokenExchangeRate[cToken] = cTokenExchangeRate;
}
}
// Update the total loan
if(borrowRateIndex[_token][blockNumber] != UNIT) {
totalLoans[_token] = totalLoans[_token].mul(borrowRateIndex[_token][blockNumber])
.div(borrowRateIndex[_token][previousCheckpoint]);
}
emit UpdateIndex(_token, depositeRateIndex[_token][getBlockNumber()], borrowRateIndex[_token][getBlockNumber()]);
}
/**
* Calculate a token deposite rate of current block
* @param _token token address
* @dev This is an looking forward estimation from last checkpoint and not the exactly rate that the user will pay or earn.
*/
function depositeRateIndexNow(address _token) public view returns(uint) {
uint256 lcp = lastCheckpoint[_token];
// If this is the first checkpoint, set the index be 1.
if(lcp == 0)
return INT_UNIT;
uint256 lastDepositeRateIndex = depositeRateIndex[_token][lcp];
uint256 depositRatePerBlock = getDepositRatePerBlock(_token);
// newIndex = oldIndex*(1+r*delta_block). If delta_block = 0, i.e. the last checkpoint is current block, index doesn't change.
return lastDepositeRateIndex.mul(getBlockNumber().sub(lcp).mul(depositRatePerBlock).add(INT_UNIT)).div(INT_UNIT);
}
/**
* Calculate a token borrow rate of current block
* @param _token token address
*/
function borrowRateIndexNow(address _token) public view returns(uint) {
uint256 lcp = lastCheckpoint[_token];
// If this is the first checkpoint, set the index be 1.
if(lcp == 0)
return INT_UNIT;
uint256 lastBorrowRateIndex = borrowRateIndex[_token][lcp];
uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token);
return lastBorrowRateIndex.mul(getBlockNumber().sub(lcp).mul(borrowRatePerBlock).add(INT_UNIT)).div(INT_UNIT);
}
/**
* Get the state of the given token
* @param _token token address
*/
function getTokenState(address _token) public view returns (uint256 deposits, uint256 loans, uint256 reserveBalance, uint256 remainingAssets){
return (
getTotalDepositStore(_token),
totalLoans[_token],
totalReserve[_token],
totalReserve[_token].add(totalCompound[globalConfig.tokenInfoRegistry().getCToken(_token)])
);
}
function getPoolAmount(address _token) public view returns(uint) {
return totalReserve[_token].add(totalCompound[globalConfig.tokenInfoRegistry().getCToken(_token)]);
}
function deposit(address _to, address _token, uint256 _amount) external onlyAuthorized {
require(_amount != 0, "Amount is zero");
// Add a new checkpoint on the index curve.
newRateIndexCheckpoint(_token);
updateDepositFINIndex(_token);
// Update tokenInfo. Add the _amount to principal, and update the last deposit block in tokenInfo
globalConfig.accounts().deposit(_to, _token, _amount);
// Update the amount of tokens in compound and loans, i.e. derive the new values
// of C (Compound Ratio) and U (Utilization Ratio).
uint compoundAmount = update(_token, _amount, ActionType.DepositAction);
if(compoundAmount > 0) {
globalConfig.savingAccount().toCompound(_token, compoundAmount);
}
}
function borrow(address _from, address _token, uint256 _amount) external onlyAuthorized {
// Add a new checkpoint on the index curve.
newRateIndexCheckpoint(_token);
updateBorrowFINIndex(_token);
// Update tokenInfo for the user
globalConfig.accounts().borrow(_from, _token, _amount);
// Update pool balance
// Update the amount of tokens in compound and loans, i.e. derive the new values
// of C (Compound Ratio) and U (Utilization Ratio).
uint compoundAmount = update(_token, _amount, ActionType.BorrowAction);
if(compoundAmount > 0) {
globalConfig.savingAccount().fromCompound(_token, compoundAmount);
}
}
function repay(address _to, address _token, uint256 _amount) external onlyAuthorized returns(uint) {
// Add a new checkpoint on the index curve.
newRateIndexCheckpoint(_token);
updateBorrowFINIndex(_token);
// Sanity check
require(globalConfig.accounts().getBorrowPrincipal(_to, _token) > 0,
"Token BorrowPrincipal must be greater than 0. To deposit balance, please use deposit button."
);
// Update tokenInfo
uint256 remain = globalConfig.accounts().repay(_to, _token, _amount);
// Update the amount of tokens in compound and loans, i.e. derive the new values
// of C (Compound Ratio) and U (Utilization Ratio).
uint compoundAmount = update(_token, _amount.sub(remain), ActionType.RepayAction);
if(compoundAmount > 0) {
globalConfig.savingAccount().toCompound(_token, compoundAmount);
}
// Return actual amount repaid
return _amount.sub(remain);
}
/**
* Withdraw a token from an address
* @param _from address to be withdrawn from
* @param _token token address
* @param _amount amount to be withdrawn
* @return The actually amount withdrawed, which will be the amount requested minus the commission fee.
*/
function withdraw(address _from, address _token, uint256 _amount) external onlyAuthorized returns(uint) {
require(_amount != 0, "Amount is zero");
// Add a new checkpoint on the index curve.
newRateIndexCheckpoint(_token);
updateDepositFINIndex(_token);
// Withdraw from the account
uint amount = globalConfig.accounts().withdraw(_from, _token, _amount);
// Update pool balance
// Update the amount of tokens in compound and loans, i.e. derive the new values
// of C (Compound Ratio) and U (Utilization Ratio).
uint compoundAmount = update(_token, amount, ActionType.WithdrawAction);
// Check if there are enough tokens in the pool.
if(compoundAmount > 0) {
globalConfig.savingAccount().fromCompound(_token, compoundAmount);
}
return amount;
}
/**
* Get current block number
* @return the current block number
*/
function getBlockNumber() private view returns (uint) {
return block.number;
}
function version() public pure returns(string memory) {
return "v1.2.0";
}
} | Add a new checkpoint on the index curve. Update tokenInfo. Add the _amount to principal, and update the last deposit block in tokenInfo Update the amount of tokens in compound and loans, i.e. derive the new values of C (Compound Ratio) and U (Utilization Ratio). | function deposit(address _to, address _token, uint256 _amount) external onlyAuthorized {
require(_amount != 0, "Amount is zero");
newRateIndexCheckpoint(_token);
updateDepositFINIndex(_token);
globalConfig.accounts().deposit(_to, _token, _amount);
uint compoundAmount = update(_token, _amount, ActionType.DepositAction);
if(compoundAmount > 0) {
globalConfig.savingAccount().toCompound(_token, compoundAmount);
}
}
| 5,774,315 | [
1,
986,
279,
394,
9776,
603,
326,
770,
8882,
18,
2315,
1147,
966,
18,
1436,
326,
389,
8949,
358,
8897,
16,
471,
1089,
326,
1142,
443,
1724,
1203,
316,
1147,
966,
2315,
326,
3844,
434,
2430,
316,
11360,
471,
437,
634,
16,
277,
18,
73,
18,
14763,
326,
394,
924,
434,
385,
261,
16835,
534,
4197,
13,
471,
587,
261,
29180,
534,
4197,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
443,
1724,
12,
2867,
389,
869,
16,
1758,
389,
2316,
16,
2254,
5034,
389,
8949,
13,
3903,
1338,
15341,
288,
203,
203,
3639,
2583,
24899,
8949,
480,
374,
16,
315,
6275,
353,
3634,
8863,
203,
203,
3639,
394,
4727,
1016,
14431,
24899,
2316,
1769,
203,
3639,
1089,
758,
1724,
7263,
1016,
24899,
2316,
1769,
203,
203,
3639,
2552,
809,
18,
13739,
7675,
323,
1724,
24899,
869,
16,
389,
2316,
16,
389,
8949,
1769,
203,
203,
3639,
2254,
11360,
6275,
273,
1089,
24899,
2316,
16,
389,
8949,
16,
4382,
559,
18,
758,
1724,
1803,
1769,
203,
203,
3639,
309,
12,
22585,
6275,
405,
374,
13,
288,
203,
5411,
2552,
809,
18,
87,
5339,
3032,
7675,
869,
16835,
24899,
2316,
16,
11360,
6275,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.11;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Authorizable
* @dev Allows to authorize access to certain function calls
*
* ABI
* [{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]
*/
contract Authorizable {
address[] authorizers;
mapping(address => uint) authorizerIndex;
/**
* @dev Throws if called by any account tat is not authorized.
*/
modifier onlyAuthorized {
require(isAuthorized(msg.sender));
_;
}
/**
* @dev Contructor that authorizes the msg.sender.
*/
function Authorizable() {
authorizers.length = 2;
authorizers[1] = msg.sender;
authorizerIndex[msg.sender] = 1;
}
/**
* @dev Function to get a specific authorizer
* @param authorizerIndex index of the authorizer to be retrieved.
* @return The address of the authorizer.
*/
function getAuthorizer(uint authorizerIndex) external constant returns(address) {
return address(authorizers[authorizerIndex + 1]);
}
/**
* @dev Function to check if an address is authorized
* @param _addr the address to check if it is authorized.
* @return boolean flag if address is authorized.
*/
function isAuthorized(address _addr) constant returns(bool) {
return authorizerIndex[_addr] > 0;
}
/**
* @dev Function to add a new authorizer
* @param _addr the address to add as a new authorizer.
*/
function addAuthorized(address _addr) external onlyAuthorized {
authorizerIndex[_addr] = authorizers.length;
authorizers.length++;
authorizers[authorizers.length - 1] = _addr;
}
}
/**
* @title ExchangeRate
* @dev Allows updating and retrieveing of Conversion Rates for PAY tokens
*
* ABI
* [{"constant":false,"inputs":[{"name":"_symbol","type":"string"},{"name":"_rate","type":"uint256"}],"name":"updateRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"data","type":"uint256[]"}],"name":"updateRates","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_symbol","type":"string"}],"name":"getRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"rates","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"timestamp","type":"uint256"},{"indexed":false,"name":"symbol","type":"bytes32"},{"indexed":false,"name":"rate","type":"uint256"}],"name":"RateUpdated","type":"event"}]
*/
contract ExchangeRate is Ownable {
event RateUpdated(uint timestamp, bytes32 symbol, uint rate);
mapping(bytes32 => uint) public rates;
/**
* @dev Allows the current owner to update a single rate.
* @param _symbol The symbol to be updated.
* @param _rate the rate for the symbol.
*/
function updateRate(string _symbol, uint _rate) public onlyOwner {
rates[sha3(_symbol)] = _rate;
RateUpdated(now, sha3(_symbol), _rate);
}
/**
* @dev Allows the current owner to update multiple rates.
* @param data an array that alternates sha3 hashes of the symbol and the corresponding rate .
*/
function updateRates(uint[] data) public onlyOwner {
if (data.length % 2 > 0)
throw;
uint i = 0;
while (i < data.length / 2) {
bytes32 symbol = bytes32(data[i * 2]);
uint rate = data[i * 2 + 1];
rates[symbol] = rate;
RateUpdated(now, symbol, rate);
i++;
}
}
/**
* @dev Allows the anyone to read the current rate.
* @param _symbol the symbol to be retrieved.
*/
function getRate(string _symbol) public constant returns(uint) {
return rates[sha3(_symbol)];
}
}
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
/**
* @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, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implemantation of the basic standart token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// 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
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint value);
event MintFinished();
bool public mintingFinished = false;
uint public totalSupply = 0;
modifier canMint() {
if(mintingFinished) throw;
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve 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, uint _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title PayToken
* @dev The main PAY token contract
*
* ABI
* [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"startTrading","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"tradingStarted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]
*/
contract PayToken is MintableToken {
string public name = "TenX Pay Token";
string public symbol = "PAY";
uint public decimals = 18;
bool public tradingStarted = false;
/**
* @dev modifier that throws if trading has not started yet
*/
modifier hasStartedTrading() {
require(tradingStarted);
_;
}
/**
* @dev Allows the owner to enable the trading. This can not be undone
*/
function startTrading() onlyOwner {
tradingStarted = true;
}
/**
* @dev Allows anyone to transfer the PAY tokens once trading has started
* @param _to the recipient address of the tokens.
* @param _value number of tokens to be transfered.
*/
function transfer(address _to, uint _value) hasStartedTrading {
super.transfer(_to, _value);
}
/**
* @dev Allows anyone to transfer the PAY tokens once trading has started
* @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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) hasStartedTrading {
super.transferFrom(_from, _to, _value);
}
}
/**
* @title MainSale
* @dev The main PAY token sale contract
*
* ABI
* [{"constant":false,"inputs":[{"name":"_multisigVault","type":"address"}],"name":"setMultisigVault","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"exchangeRate","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"altDeposits","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"},{"name":"tokens","type":"uint256"}],"name":"authorizedCreateTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_exchangeRate","type":"address"}],"name":"setExchangeRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"}],"name":"retrieveTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"totalAltDeposits","type":"uint256"}],"name":"setAltDeposit","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"start","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"}],"name":"createTokens","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"multisigVault","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hardcap","type":"uint256"}],"name":"setHardCap","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_start","type":"uint256"}],"name":"setStart","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"token","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"ether_amount","type":"uint256"},{"indexed":false,"name":"pay_amount","type":"uint256"},{"indexed":false,"name":"exchangerate","type":"uint256"}],"name":"TokenSold","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"pay_amount","type":"uint256"}],"name":"AuthorizedCreate","type":"event"},{"anonymous":false,"inputs":[],"name":"MainSaleClosed","type":"event"}]
*/
contract MainSale is Ownable, Authorizable {
using SafeMath for uint;
event TokenSold(address recipient, uint ether_amount, uint pay_amount, uint exchangerate);
event AuthorizedCreate(address recipient, uint pay_amount);
event MainSaleClosed();
PayToken public token = new PayToken();
address public multisigVault;
uint hardcap = 200000 ether;
ExchangeRate public exchangeRate;
uint public altDeposits = 0;
uint public start = 1498302000; //new Date("Jun 24 2017 11:00:00 GMT").getTime() / 1000
/**
* @dev modifier to allow token creation only when the sale IS ON
*/
modifier saleIsOn() {
require(now > start && now < start + 28 days);
_;
}
/**
* @dev modifier to allow token creation only when the hardcap has not been reached
*/
modifier isUnderHardCap() {
require(multisigVault.balance + altDeposits <= hardcap);
_;
}
/**
* @dev Allows anyone to create tokens by depositing ether.
* @param recipient the recipient to receive tokens.
*/
function createTokens(address recipient) public isUnderHardCap saleIsOn payable {
uint rate = exchangeRate.getRate("ETH");
uint tokens = rate.mul(msg.value).div(1 ether);
token.mint(recipient, tokens);
require(multisigVault.send(msg.value));
TokenSold(recipient, msg.value, tokens, rate);
}
/**
* @dev Allows to set the toal alt deposit measured in ETH to make sure the hardcap includes other deposits
* @param totalAltDeposits total amount ETH equivalent
*/
function setAltDeposit(uint totalAltDeposits) public onlyOwner {
altDeposits = totalAltDeposits;
}
/**
* @dev Allows authorized acces to create tokens. This is used for Bitcoin and ERC20 deposits
* @param recipient the recipient to receive tokens.
* @param tokens number of tokens to be created.
*/
function authorizedCreateTokens(address recipient, uint tokens) public onlyAuthorized {
token.mint(recipient, tokens);
AuthorizedCreate(recipient, tokens);
}
/**
* @dev Allows the owner to set the hardcap.
* @param _hardcap the new hardcap
*/
function setHardCap(uint _hardcap) public onlyOwner {
hardcap = _hardcap;
}
/**
* @dev Allows the owner to set the starting time.
* @param _start the new _start
*/
function setStart(uint _start) public onlyOwner {
start = _start;
}
/**
* @dev Allows the owner to set the multisig contract.
* @param _multisigVault the multisig contract address
*/
function setMultisigVault(address _multisigVault) public onlyOwner {
if (_multisigVault != address(0)) {
multisigVault = _multisigVault;
}
}
/**
* @dev Allows the owner to set the exchangerate contract.
* @param _exchangeRate the exchangerate address
*/
function setExchangeRate(address _exchangeRate) public onlyOwner {
exchangeRate = ExchangeRate(_exchangeRate);
}
/**
* @dev Allows the owner to finish the minting. This will create the
* restricted tokens and then close the minting.
* Then the ownership of the PAY token contract is transfered
* to this owner.
*/
function finishMinting() public onlyOwner {
uint issuedTokenSupply = token.totalSupply();
uint restrictedTokens = issuedTokenSupply.mul(49).div(51);
token.mint(multisigVault, restrictedTokens);
token.finishMinting();
token.transferOwnership(owner);
MainSaleClosed();
}
/**
* @dev Allows the owner to transfer ERC20 tokens to the multi sig vault
* @param _token the contract address of the ERC20 contract
*/
function retrieveTokens(address _token) public onlyOwner {
ERC20 token = ERC20(_token);
token.transfer(multisigVault, token.balanceOf(this));
}
/**
* @dev Fallback function which receives ether and created the appropriate number of tokens for the
* msg.sender.
*/
function() external payable {
createTokens(msg.sender);
}
} | * @dev Allows the owner to set the hardcap. @param _hardcap the new hardcap/ | function setHardCap(uint _hardcap) public onlyOwner {
hardcap = _hardcap;
}
| 986,443 | [
1,
19132,
326,
3410,
358,
444,
326,
7877,
5909,
18,
225,
389,
20379,
5909,
326,
394,
7877,
5909,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
444,
29601,
4664,
12,
11890,
389,
20379,
5909,
13,
1071,
1338,
5541,
288,
203,
565,
7877,
5909,
273,
389,
20379,
5909,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.7.2;
// SPDX-License-Identifier: JPLv1.2-NRS Public License; Special Conditions with IVT being the Token, ItoVault the copyright holder
import "./SafeMath.sol";
import "./GeneralToken.sol";
contract VaultSystem {
using SafeMath for uint256;
event loguint(string name, uint value);
GeneralToken public vSYMToken;
GeneralToken public ivtToken;
// NB: None of the storage variables below should store numbers greater than 1E36. uint256 overflow above 1E73.
// So it is safe to mul two numbers always. But to mul more than 2 requires decimal counting.
uint public weiPervSYM = 10 ** 18;
uint public maxvSYME18 = 10000 * 10 ** 18; // Upper Bound on Number of vSYM tokens
uint public outstandingvSYME18 = 0; // Current outstanding vSYM tokens
// Forward (not counter) Vault System
uint public initialLTVE10 = 7 * 10 ** 9; // Maximum starting loan to value of a vault [Integer / 1E10]
uint public maintLTVE10 = 8 * 10 ** 9; // Maximum maintnenance loan to value of a vault [Integer / 1E10]
uint public liqPenaltyE10 = 1 * 10 ** 9; // Bonus paid to any address for liquidating non-compliant
// contract [Integer / 1E10]
// In this system, individual vaults *are* addresses. Instances of vaults then are mapped by bare address
// Each vault has an "asset" side and a "debt" side
mapping(address => uint) public weiAsset; // Weis the Vault owns -- the asset side
mapping(address => uint) public vSYMDebtE18; // vSYM -- the debt side of the balance sheet of each Vault
// Counter Vault Contract
uint public initialLTVCounterVaultE10 = 7 * 10 ** 9; // Maximum starting loan to value of a vault [Integer / 1E10]
uint public maintLTVCounterVaultE10 = 8 * 10 ** 9; // Maximum maintnenance loan to value of a vault [Integer / 1E10]
uint public liqPenaltyCounterVaultE10 = 1 * 10 ** 9; // Bonus paid to any address for liquidating non-compliant
// contract [Integer / 1E10]
mapping(address => uint) public vSYMAssetCounterVaultE18; // vSYM deposited in inverse vault
mapping(address => uint) public weiDebtCounterVault; // weiDebtCounterVault
// The following variables track all Vaults. Not strictly needed, but helps liquidate non-compliant vaults
mapping(address => bool) public isAddressRegistered; // Forward map to emulate a "set" struct
address[] public registeredAddresses; // Backward map for "set" struct
address payable public owner; // owner is also governor here. to be passed to WATDAO in the future
address payable public oracle; //
bool public inGlobalSettlement = false;
uint public globalSettlementStartTime;
uint public settledWeiPervSYM;
bool public isGloballySettled = false;
uint public lastOracleTime;
bool public oracleChallenged = false; // Is the whitelisted oracle (system) in challenge?
uint public lastChallengeValue; // The weiPervSYM value of the last challenge [Integer atomic weis per 1 unit SPX (e.g. SPX ~ $3300 in Oct 2020)]
uint public lastChallengeIVT; // The WATs staked in the last challenge [WAT atomic units]
uint public lastChallengeTime; // The time of the last challenge, used for challenge expiry[Seconds since Epoch]
uint[] public challengeIVTokens; // Dynamic array of all challenges, integer indexed to match analagous arrays, used like a stack in code
uint[] public challengeValues; // Dynamic array of all challenges, integer indexed, used like a stack in code
address[] public challengers; // Dynamic array of all challengers, integer indexed, used like a stack in code
constructor() {
owner = msg.sender;
oracle = msg.sender;
vSYMToken = new GeneralToken(10 ** 30, address(this), "vVTI Token V_1_0_0", "vVTI V1_0"); // 18 decimals after the point, 12 before
ivtToken = GeneralToken(address(0xb5BC0481ff9EF553F11f031A469cd9DF71280A27));
}
// Oracle Functions
function oracleUpdateweiPervSYM(uint _weiPervSYM) public {
require(msg.sender == oracle, "Disallowed: You are not oracle");
weiPervSYM = _weiPervSYM;
lastOracleTime = block.timestamp;
}
// Governance Functions
function govUpdateinitialLTVE10(uint _initialLTVE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
initialLTVE10 = _initialLTVE10;
}
function govUpdatemaintLTVE10(uint _maintLTVE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
maintLTVE10 = _maintLTVE10;
}
function govUpdateliqPenaltyE10(uint _liqPenaltyE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
liqPenaltyE10 = _liqPenaltyE10;
}
function govUpdateinitialLTVCounterVaultE10(uint _initialLTVCounterVaultE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
initialLTVCounterVaultE10 = _initialLTVCounterVaultE10;
}
function govUpdatemaintLTVCounterVaultE10(uint _maintLTVCounterVaultE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
maintLTVCounterVaultE10 = _maintLTVCounterVaultE10;
}
function govUpdateliqPenaltyCounterVaultE10(uint _liqPenaltyCounterVaultE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
liqPenaltyCounterVaultE10 = _liqPenaltyCounterVaultE10;
}
function govChangeOwner(address payable _owner) public {
require(msg.sender == owner, "Disallowed: You are not governance");
owner = _owner;
}
function govChangeOracle(address payable _oracle) public {
require(msg.sender == owner, "Disallowed: You are not governance");
oracle = _oracle;
}
function govChangeMaxvSYME18(uint _maxvSYME18) public {
require(msg.sender == owner, "Disallowed: You are not governance");
maxvSYME18 = _maxvSYME18;
}
function govStartGlobalSettlement() public {
require(msg.sender == owner, "Disallowed: You are not governance");
inGlobalSettlement = true;
globalSettlementStartTime = block.timestamp;
}
// Vault Functions
function depositWEI() public payable { // same as receive fallback; but explictily declared for symmetry
require(msg.value > 0, "Must Deposit Nonzero Wei");
weiAsset[msg.sender] = weiAsset[msg.sender].add( msg.value );
if(isAddressRegistered[msg.sender] != true) { // if user was not registered before
isAddressRegistered[msg.sender] = true;
registeredAddresses.push(msg.sender);
}
}
receive() external payable { // same as receive fallback; but explictily declared for symmetry
require(msg.value > 0, "Must Deposit Nonzero Wei");
// Receiving is automatic so double entry accounting not possible here
weiAsset[msg.sender] = weiAsset[msg.sender].add( msg.value );
if(isAddressRegistered[msg.sender] != true) { // if user was not registered before
isAddressRegistered[msg.sender] = true;
registeredAddresses.push(msg.sender);
}
}
function withdrawWEI(uint _weiWithdraw) public { // NB: Security model is against msg.sender
// presuming contract withdrawal is from own vault
require( _weiWithdraw < 10 ** 30, "Protective max bound for uint argument");
// Maintenence Equation: (vSYMDebtE18/1E18) * weiPervSYM <= (weiAsset) * (initialLTVE10/1E10)
// I need: (vSYMDebtE18)/1E18 * weiPervSYM <= (weiAsset - _weiWithdraw) * (initialLTVE10/1E10)
uint LHS = vSYMDebtE18[msg.sender].mul( weiPervSYM ).mul( 10 ** 10 );
uint RHS = (weiAsset[msg.sender].sub( _weiWithdraw )).mul( initialLTVE10 ).mul( 10 ** 18 );
require ( LHS <= RHS, "Your initial margin is insufficient for withdrawing.");
// Double Entry Accounting
weiAsset[msg.sender] = weiAsset[msg.sender].sub( _weiWithdraw ); // penalize wei deposited before sending money out
msg.sender.transfer(_weiWithdraw);
}
function lendvSYM(uint _vSYMLendE18) public {
//presuming message sender is using his own vault
require(_vSYMLendE18 < 10 ** 30, "Protective max bound for uint argument");
require(outstandingvSYME18.add( _vSYMLendE18 ) <= maxvSYME18, "Current version limits max amount of vSYM possible");
// Maintenence Equation: (vSYMDebtE18/1E18) * weiPervSYM <= (weiAsset) * (initialLTVE10/1E10)
// I need: (_vSYMLendE18 + vSYMDebtE18)/1E18 * weiPervSYM < weiAsset * (initialLTVE10/1E10)
uint LHS = vSYMDebtE18[msg.sender].add( _vSYMLendE18 ).mul( weiPervSYM ).mul( 10 ** 10 );
uint RHS = weiAsset[msg.sender].mul( initialLTVE10 ).mul( 10 ** 18 );
require(LHS < RHS, "Your initial margin is insufficient for lending");
// Double Entry Accounting
vSYMDebtE18[msg.sender] = vSYMDebtE18[msg.sender].add( _vSYMLendE18 ); // penalize debt first.
outstandingvSYME18 = outstandingvSYME18.add(_vSYMLendE18);
vSYMToken.transfer(msg.sender, _vSYMLendE18);
}
function repayvSYM(uint _vSYMRepayE18) public {
require(_vSYMRepayE18 < 10 ** 30, "Protective max bound for uint argument");
vSYMToken.ownerApprove(msg.sender, _vSYMRepayE18);
// Double Entry Accounting
vSYMToken.transferFrom(msg.sender, address(this), _vSYMRepayE18); // the actual deduction from the token contract
vSYMDebtE18[msg.sender] = vSYMDebtE18[msg.sender].sub( _vSYMRepayE18 );
outstandingvSYME18 = outstandingvSYME18.sub(_vSYMRepayE18);
}
function liquidateNonCompliant(uint _vSYMProvidedE18, address payable target_address) public { // liquidates a portion of the contract for non-compliance
// While it possible to have a more complex liquidation system, since liqudations are off-equilibrium, for the MVP
// We have decided we want overly aggressive liqudiations
// Maintenence Equation: (vSYMDebtE18/1E18) * weiPervSYM <= (weiAsset) * (maintLTVE10/1E10)
// For a violation, the above will be flipped: (vSYMDebtE18/1E18) * weiPervSYM > (weiAsset) * (maintLTVE10/1E10)
require( _vSYMProvidedE18 <= vSYMDebtE18[target_address], "You cannot provide more vSYM than vSYMDebt outstanding");
uint LHS = vSYMDebtE18[target_address].mul( weiPervSYM ).mul( 10 ** 10);
uint RHS = weiAsset[target_address].mul( maintLTVE10 ).mul( 10 ** 18);
require(LHS > RHS, "Current contract is within maintainance margin, so you cannot run this");
// If this vault is underwater-with-respect-to-rewards (different than noncompliant), liquidation is pro-rata
// underater iff: weiAsset[target_address] < vSYMDebtE18[target_address]/1E18 * weiPervSYM * (liqPenaltyE10+1E10)/1E10
uint LHS2 = weiAsset[target_address].mul( 10 ** 18 ).mul( 10 ** 10);
uint RHS2 = vSYMDebtE18[target_address].mul( weiPervSYM ).mul( liqPenaltyE10.add( 10 ** 10 ));
uint weiClaim;
if( LHS2 < RHS2 ) { // pro-rata claim
// weiClaim = ( _vSYMProvidedE18 / vSYMDebtE18[target_address]) * weiAsset[target_address];
weiClaim = _vSYMProvidedE18.mul( weiAsset[target_address] ).div( vSYMDebtE18[target_address] );
} else {
// maxWeiClaim = _vSYMProvidedE18/1E18 * weiPervSYM * (1+liqPenaltyE10/1E10)
weiClaim = _vSYMProvidedE18.mul( weiPervSYM ).mul( liqPenaltyE10.add( 10 ** 10 )).div( 10 ** 18 ).div( 10 ** 10 );
}
require(weiClaim <= weiAsset[target_address], "Code Error if you reached this point");
// Double Entry Accounting for returning vSYM Debt back
vSYMToken.ownerApprove(msg.sender, _vSYMProvidedE18);
vSYMToken.transferFrom(msg.sender, address(this), _vSYMProvidedE18); // the actual deduction from the token contract
vSYMDebtE18[target_address] = vSYMDebtE18[target_address].sub( _vSYMProvidedE18 );
outstandingvSYME18 = outstandingvSYME18.sub( _vSYMProvidedE18 );
// Double Entry Accounting for deducting the vault's assets
weiAsset[target_address] = weiAsset[target_address].sub( weiClaim );
msg.sender.transfer( weiClaim );
}
// Counter Vault Functions
function depositvSYMCounterVault(uint _vSYMDepositE18) public {
require( _vSYMDepositE18 < 10 ** 30, "Protective max bound for uint argument");
// Transfer Tokens from sender, then double-entry account for it
vSYMToken.ownerApprove(msg.sender, _vSYMDepositE18);
vSYMToken.transferFrom(msg.sender, address(this), _vSYMDepositE18);
vSYMAssetCounterVaultE18[msg.sender] = vSYMAssetCounterVaultE18[msg.sender].add(_vSYMDepositE18);
if(isAddressRegistered[msg.sender] != true) { // if user was not registered before
isAddressRegistered[msg.sender] = true;
registeredAddresses.push(msg.sender);
}
}
function withdrawvSYMCounterVault(uint _vSYMWithdrawE18) public {
require( _vSYMWithdrawE18 < 10 ** 30, "Protective max bound for uint argument");
// Master equation for countervault: (weiDebtCounterVault ) < (vSYMAssetCounterVaultE18)/1E18 * weiPervSYM * (initialLTVCounterVaultE10/1E10)
// I need: (weiDebtCounterVault ) < (vSYMAssetCounterVaultE18 - _vSYMLendE18)/1E18 * weiPervSYM * (initialLTVCounterVaultE10/1E10)
uint LHS = weiDebtCounterVault[msg.sender].mul( 10 ** 10 ).mul( 10 ** 18 );
uint RHS = vSYMAssetCounterVaultE18[msg.sender].sub( _vSYMWithdrawE18 ).mul( weiPervSYM ).mul( initialLTVCounterVaultE10 );
require ( LHS <= RHS, 'Your initial margin is insufficient for withdrawing.' );
vSYMAssetCounterVaultE18[msg.sender] = vSYMAssetCounterVaultE18[msg.sender].sub( _vSYMWithdrawE18 ); // Penalize Account First
vSYMToken.transfer(msg.sender, _vSYMWithdrawE18);
}
function lendWeiCounterVault(uint _weiLend) public {
//presuming message sender is using his own vault
require(_weiLend < 10 ** 30, "Protective Max Bound for Input Hit");
// Master equation for countervault: (weiDebtCounterVault ) < (vSYMAssetCounterVaultE18)/1E18 * weiPervSYM * (initialLTVCounterVaultE10/1E10)
// I need: (weiDebtCounterVault + _weiWithdraw ) < weiPervSYM * (vSYMAssetCounterVaultE18/1E18) * (initialLTVCounterVaultE10/1E10)
uint LHS = weiDebtCounterVault[msg.sender].add( _weiLend ).mul( 10** 18 ).mul( 10 ** 10 );
uint RHS = weiPervSYM.mul( vSYMAssetCounterVaultE18[msg.sender] ).mul( initialLTVCounterVaultE10 );
require(LHS <= RHS, "Your initial margin is insufficient for lending.");
// Double-entry accounting
weiDebtCounterVault[msg.sender] = weiDebtCounterVault[msg.sender].add( _weiLend ); // penalize debt first.
msg.sender.transfer(_weiLend);
}
function repayWeiCounterVault() public payable {
require(msg.value < 10 ** 30, "Protective Max Bound for Input Hit");
require(msg.value <= weiDebtCounterVault[msg.sender], "You cannot pay down more Wei debt than exists in this counterVault");
// Single entry accounting
weiDebtCounterVault[msg.sender] = weiDebtCounterVault[msg.sender].sub( msg.value );
}
function liquidateNonCompliantCounterVault(address payable _targetCounterVault) payable public { // liquidates a portion of the counterVault for non-compliance
// Security Presumption here is against favor of the runner of this function
require( msg.value < 10 ** 30 , "Protective Max Bound for WEI Hit");
require( msg.value <= weiDebtCounterVault[_targetCounterVault], "You cannot provide more Wei than Wei debt outstanding");
// Vault Needs to be in Violation: (weiDebtCounterVault ) > (vSYMAssetCounterVaultE18)/1E18 * weiPervSYM * (maintLTVE10InverseVault/1E10)
uint LHS = weiDebtCounterVault[_targetCounterVault].mul( 10 ** 18 ).mul( 10 ** 10 );
uint RHS = vSYMAssetCounterVaultE18[_targetCounterVault].mul( weiPervSYM ).mul( maintLTVCounterVaultE10 );
emit loguint("RHS", RHS);
emit loguint("LHS", LHS);
require(LHS > RHS, "Current contract is within maintenence margin");
// If this Counter Vault is underwater-with-respect-to-rewards (different than noncompliant), liquidation is pro-rata
// underater iff: vSYMAssetCounterVaultE18[_targetCounterVault] < (weiDebtCounterVault[_targetCounterVault]/ weiPervSYM) * 1E18 * (liqPenaltyCounterVaultE10+1E10)/1E10
uint LHS2 = vSYMAssetCounterVaultE18[_targetCounterVault];
uint RHS2 = weiDebtCounterVault[_targetCounterVault].mul( liqPenaltyCounterVaultE10.add( 10 ** 10 )).mul( 10 ** 8 ).div( weiPervSYM );
emit loguint("RHS2", RHS2);
emit loguint("LHS2", LHS2);
uint vSYMClaimE18;
if( LHS2 < RHS2 ) { // if vault is rewards-underwater, pro-rate
// vSYMClaimE18 = ( msg.value / weiDebtCounterVault[_targetCounterVault]) * vSYMAssetCounterVaultE18[_targetCounterVault];
vSYMClaimE18 = msg.value.mul( vSYMAssetCounterVaultE18[_targetCounterVault] ).div( weiDebtCounterVault[_targetCounterVault] );
require(vSYMClaimE18 <= vSYMAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 1 if you reached this point");
} else { // if we have more than enough assets in this countervault
// vSYMClaimE18 = (msg.value / weiPervSYM) * 1E18 * (1E10+liqPenaltyE10) /1E10
vSYMClaimE18 = msg.value.mul( liqPenaltyCounterVaultE10.add( 10 ** 10 )).mul( 10 ** 8 ).div(weiPervSYM) ;
require(vSYMClaimE18 <= vSYMAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 2 if you reached this point");
}
// Single Entry Accounting for Returning the wei Debt
weiDebtCounterVault[_targetCounterVault] = weiDebtCounterVault[_targetCounterVault].sub( msg.value );
// Double Entry Accounting
vSYMAssetCounterVaultE18[_targetCounterVault] = vSYMAssetCounterVaultE18[_targetCounterVault].sub( vSYMClaimE18 ); // Amount of Assets to Transfer override
vSYMToken.transfer( msg.sender , vSYMClaimE18 );
}
function partial1LiquidateNonCompliantCounterVault(address payable _targetCounterVault) payable public returns(uint, uint) { // liquidates a portion of the counterVault for non-compliance
// Security Presumption here is against favor of the runner of this function
require( msg.value < 10 ** 30 , "Protective Max Bound for WEI Hit");
require( msg.value <= weiDebtCounterVault[_targetCounterVault], "You cannot provide more Wei than Wei debt outstanding");
// Vault Needs to be in Violation: (weiDebtCounterVault ) > (vSYMAssetCounterVaultE18)/1E18 * weiPervSYM * (maintLTVE10InverseVault/1E10)
uint LHS = weiDebtCounterVault[_targetCounterVault].mul( 10 ** 18 ).mul( 10 ** 10 );
uint RHS = vSYMAssetCounterVaultE18[_targetCounterVault].mul( weiPervSYM ).mul( maintLTVCounterVaultE10 );
require(LHS > RHS, "Current contract is within maintenence margin");
return(LHS, RHS);
}
function partial2LiquidateNonCompliantCounterVault(address payable _targetCounterVault) payable public returns(uint, uint) { // liquidates a portion of the counterVault for non-compliance
// Security Presumption here is against favor of the runner of this function
require( msg.value < 10 ** 30 , "Protective Max Bound for WEI Hit");
require( msg.value <= weiDebtCounterVault[_targetCounterVault], "You cannot provide more Wei than Wei debt outstanding");
// Vault Needs to be in Violation: (weiDebtCounterVault ) > (vSYMAssetCounterVaultE18)/1E18 * weiPervSYM * (maintLTVE10InverseVault/1E10)
// If this Counter Vault is underwater-with-respect-to-rewards (different than noncompliant), liquidation is pro-rata
// underater iff: vSYMAssetCounterVaultE18[_targetCounterVault] < (weiDebtCounterVault[_targetCounterVault]/ weiPervSYM) * 1E18 * (liqPenaltyCounterVaultE10+1E10)/1E10
uint LHS2 = vSYMAssetCounterVaultE18[_targetCounterVault];
uint RHS2 = weiDebtCounterVault[_targetCounterVault].mul( liqPenaltyCounterVaultE10.add( 10 ** 10 )).mul( 10 ** 8 ).div( weiPervSYM );
return(LHS2, RHS2);
}
function findNoncompliantVaults(uint _limitNum) public view returns(address[] memory, uint[] memory, uint[] memory, uint[] memory, uint[] memory, uint) { // Return the first N noncompliant vaults
require(_limitNum > 0, 'Must run this on a positive integer');
address[] memory noncompliantAddresses = new address[](_limitNum);
uint[] memory LHSs_vault = new uint[](_limitNum);
uint[] memory RHSs_vault = new uint[](_limitNum);
uint[] memory LHSs_counterVault = new uint[](_limitNum);
uint[] memory RHSs_counterVault = new uint[](_limitNum);
uint j = 0; // Iterator up to _limitNum
for (uint i=0; i<registeredAddresses.length; i++) {
if(j>= _limitNum) {
break;
}
// Vault maintainance margin violation: (vSYMDebtE18)/1E18 * weiPervSYM > weiAsset * (maintLTVE10)/1E10 for a violation
uint LHS_vault = vSYMDebtE18[registeredAddresses[i]].mul(weiPervSYM);
uint RHS_vault = weiAsset[registeredAddresses[i]].mul( maintLTVE10 ).mul( 10 ** 8);
// Countervault maintenance margin violation: (weiDebtCounterVault ) > (vSYMAssetCounterVaultE18)/1E18 * weiPervSYM * (maintLTVE10InverseVault/1E10)
uint LHS_counterVault = weiDebtCounterVault[registeredAddresses[i]].mul( 10 ** 18 ).mul( 10 ** 10 );
uint RHS_counterVault = vSYMAssetCounterVaultE18[registeredAddresses[i]].mul( weiPervSYM ).mul( maintLTVCounterVaultE10 );
if( (LHS_vault > RHS_vault) || (LHS_counterVault > RHS_counterVault) ) {
noncompliantAddresses[j] = registeredAddresses[i];
LHSs_vault[j] = LHS_vault;
RHSs_vault[j] = RHS_vault;
LHSs_counterVault[j] = LHS_counterVault;
RHSs_counterVault[j] = RHS_counterVault;
j = j + 1;
}
}
return(noncompliantAddresses, LHSs_vault, RHSs_vault, LHSs_counterVault, RHSs_counterVault, j);
}
// The following functions are off off-equilibrium. Thus they are vetted to be safe, but not necessarily efficient/optimal.
// Global Settlement Functions
function registerGloballySettled() public { // Anyone can run this closing function
require(inGlobalSettlement, "Register function can only be run if governance has declared global settlement");
require(block.timestamp > (globalSettlementStartTime + 14 days), "Need to wait 14 days to finalize global settlement");
require(!isGloballySettled, "This function has already be run; can only be run once.");
settledWeiPervSYM = weiPervSYM;
isGloballySettled = true;
}
function settledConvertvSYMtoWei(uint _vSYMTokenToConvertE18) public {
require(isGloballySettled);
require(_vSYMTokenToConvertE18 < 10 ** 30, "Protective max bound for input hit");
uint weiToReturn = _vSYMTokenToConvertE18.mul( settledWeiPervSYM ).div( 10 ** 18); // Rounds down
// vSYM accounting is no longer double entry. Destroy vSYM to get wei
vSYMToken.ownerApprove(msg.sender, _vSYMTokenToConvertE18); // Factory gives itself approval
vSYMToken.transferFrom(msg.sender, address(this), _vSYMTokenToConvertE18); // the actual deduction from the token contract
msg.sender.transfer(weiToReturn); // return wei
}
function settledConvertVaulttoWei() public {
require(isGloballySettled);
uint weiDebt = vSYMDebtE18[msg.sender].mul( settledWeiPervSYM ).div( 10 ** 18).add( 1 ); // Round up value of debt
require(weiAsset[msg.sender] > weiDebt, "This CTV is not above water, cannot convert");
uint weiEquity = weiAsset[msg.sender] - weiDebt;
// Zero out CTV and transfer equity remaining
vSYMDebtE18[msg.sender] = 0;
weiAsset[msg.sender] = 0;
msg.sender.transfer(weiEquity);
}
// Challenge Functions -- non-optimized
function startChallengeWeiPervSYM(uint _proposedWeiPervSYM, uint _ivtStaked) public {
// Checking we're in the right state
require(lastOracleTime > 0, "Cannot challenge a newly created smart contract");
require(block.timestamp.sub( lastOracleTime ) > 14 days, "You must wait for the whitelist oracle to not respond for 14 days" );
require(_ivtStaked >= 10 * 10 ** 18, 'You must challenge with at least ten IVT');
require(_proposedWeiPervSYM != weiPervSYM, 'You do not disagree with current value of weiPervSYM');
require(oracleChallenged == false);
// Deducting tokens and crediting
uint256 allowance = ivtToken.allowance(msg.sender, address(this));
require(allowance >= _ivtStaked, 'You have not allowed this contract access to the number of IVTs you claim');
ivtToken.transferFrom(msg.sender, address(this), _ivtStaked); // the actual deduction from the token contract
// Credit this challenger
challengers.push(msg.sender);
// Start the challenge
oracleChallenged = true;
challengeValues.push(_proposedWeiPervSYM);
challengeIVTokens.push(_ivtStaked);
lastChallengeValue = _proposedWeiPervSYM;
lastChallengeTime = block.timestamp;
}
function rechallengeWeiPervSYM(uint _proposedWeiPervSYM, uint _ivtStaked) public {
require(oracleChallenged == true, "rechallenge cannot be run if challenge has not started. consider startChallengeWeiPervSYM()");
require(_ivtStaked >= lastChallengeIVT * 2, "You must double the IVT from the last challenge");
require(_proposedWeiPervSYM != lastChallengeValue, "You do not disagree with last challenge of weiPervSYM");
// Deducting tokens and crediting
uint256 allowance = ivtToken.allowance(msg.sender, address(this));
require(allowance >= _ivtStaked, 'You have not allowed this contract access to the number of WATs you claim');
ivtToken.transferFrom(msg.sender, address(this), _ivtStaked); // the actual deduction from the token contract
// Credit this challenger
challengers.push(msg.sender);
// Actually do the challenge
challengeValues.push(_proposedWeiPervSYM);
challengeIVTokens.push(_ivtStaked);
lastChallengeValue = _proposedWeiPervSYM;
lastChallengeTime = block.timestamp;
lastChallengeIVT = _ivtStaked;
}
function endChallegeWeiPerSPX() public {
require(oracleChallenged == true, "Consider startChallengeWeiPervSYM()");
require(block.timestamp.sub( lastChallengeTime ) > 2 days, "You must wait 2 days since the last challenge to end the challenge");
// This now makes effective the challenge oracle
weiPervSYM = lastChallengeValue;
// initialize cumulative counter of correct vs incorrect wats
uint incorrectIvts = 0;
uint correctIvts = 0;
// calculate the payback ratio
for(uint i = 0; i < challengeIVTokens.length; i++) {
if(challengeValues[i] == weiPervSYM) {
correctIvts += challengeIVTokens[i];
} else {
incorrectIvts += challengeIVTokens[i];
}
}
// Distribute the tokens
for(uint i = 0; i < challengeIVTokens.length; i++) { //NB -- this should not be very long due to block gas limits
if(challengeValues[i] == weiPervSYM) {
uint toTransfer = incorrectIvts.add(correctIvts).mul( challengeIVTokens[i] ).div( correctIvts );
// best practice: remove this person's credit first
challengeIVTokens[i] = 0;
vSYMToken.transfer(challengers[i], toTransfer);
} else {
// erase the challengeIVTokens
challengeIVTokens[i] = 0;
}
}
// reset arrays to zero type
delete challengeIVTokens;
delete challengeValues;
delete challengers;
lastChallengeValue = 0;
lastChallengeIVT = 0;
lastChallengeTime = 0;
// end challenge
oracleChallenged = false;
}
function detachOwner() public { // an emergency function to commitally shut off the owner account while retaining residual functionality of tokens
require(msg.sender == owner);
initialLTVE10 = 4 * 10 ** 9; // 40% LTV at start
maintLTVE10 = 5 * 10 ** 9; // 50% LTV to maintain
liqPenaltyE10 = 15 * 10 ** 8; // 15% liquidation penalty
oracle = address(0);
owner = address(0);
}
} | maxWeiClaim = _vSYMProvidedE18/1E18 * weiPervSYM * (1+liqPenaltyE10/1E10) | weiClaim = _vSYMProvidedE18.mul( weiPervSYM ).mul( liqPenaltyE10.add( 10 ** 10 )).div( 10 ** 18 ).div( 10 ** 10 );
| 29,536 | [
1,
1896,
3218,
77,
9762,
273,
389,
90,
7474,
49,
19254,
41,
2643,
19,
21,
41,
2643,
225,
732,
77,
2173,
90,
7474,
49,
225,
261,
21,
15,
549,
85,
24251,
15006,
41,
2163,
19,
21,
41,
2163,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
732,
77,
9762,
273,
389,
90,
7474,
49,
19254,
41,
2643,
18,
16411,
12,
732,
77,
2173,
90,
7474,
49,
262,
18,
16411,
12,
4501,
85,
24251,
15006,
41,
2163,
18,
1289,
12,
1728,
2826,
1728,
262,
2934,
2892,
12,
1728,
2826,
6549,
262,
18,
2892,
12,
1728,
2826,
1728,
11272,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/97/0xA6f9e2Ece33866aA621cb0c5268828A49c3aDB03/sources/_openzeppelin/contracts-upgradeable/crosschain/polygon/CrossChainEnabledPolygonChildUpgradeable.sol | ERC1967Upgrade._functionDelegateCall is private so we reproduce it here. An extra underscore prevents a name clash error. solhint-disable-next-line avoid-low-level-calls | function __functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
| 3,292,056 | [
1,
654,
39,
3657,
9599,
10784,
6315,
915,
9586,
1477,
353,
3238,
1427,
732,
283,
11776,
311,
518,
2674,
18,
1922,
2870,
13677,
17793,
279,
508,
927,
961,
555,
18,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
4543,
17,
821,
17,
2815,
17,
12550,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1001,
915,
9586,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
13,
3238,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
2583,
12,
1887,
10784,
429,
18,
291,
8924,
12,
3299,
3631,
315,
1887,
30,
7152,
745,
358,
1661,
17,
16351,
8863,
203,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
327,
892,
13,
273,
1018,
18,
22216,
1991,
12,
892,
1769,
203,
3639,
327,
5267,
10784,
429,
18,
8705,
1477,
1253,
12,
4768,
16,
327,
892,
16,
315,
1887,
30,
4587,
17,
2815,
7152,
745,
2535,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "./MixinMatchOrders.sol";
import "./MixinWrapperFunctions.sol";
import "./MixinTransferSimulator.sol";
// solhint-disable no-empty-blocks
// MixinAssetProxyDispatcher, MixinExchangeCore, MixinSignatureValidator,
// and MixinTransactions are all inherited via the other Mixins that are
// used.
contract Exchange is
LibEIP712ExchangeDomain,
MixinMatchOrders,
MixinWrapperFunctions,
MixinTransferSimulator
{
/// @dev Mixins are instantiated in the order they are inherited
/// @param chainId Chain ID of the network this contract is deployed on.
constructor (uint256 chainId)
public
LibEIP712ExchangeDomain(chainId, address(0))
{}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
contract LibEIP712ExchangeDomain {
// EIP712 Exchange Domain Name value
string constant internal _EIP712_EXCHANGE_DOMAIN_NAME = "0x Protocol";
// EIP712 Exchange Domain Version value
string constant internal _EIP712_EXCHANGE_DOMAIN_VERSION = "3.0.0";
// Hash of the EIP712 Domain Separator data
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_EXCHANGE_DOMAIN_HASH;
/// @param chainId Chain ID of the network this contract is deployed on.
/// @param verifyingContractAddressIfExists Address of the verifying contract (null if the address of this contract)
constructor (
uint256 chainId,
address verifyingContractAddressIfExists
)
public
{
address verifyingContractAddress = verifyingContractAddressIfExists == address(0) ? address(this) : verifyingContractAddressIfExists;
EIP712_EXCHANGE_DOMAIN_HASH = LibEIP712.hashEIP712Domain(
_EIP712_EXCHANGE_DOMAIN_NAME,
_EIP712_EXCHANGE_DOMAIN_VERSION,
chainId,
verifyingContractAddress
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IMatchOrders.sol";
import "./MixinExchangeCore.sol";
contract MixinMatchOrders is
MixinExchangeCore,
IMatchOrders
{
using LibBytes for bytes;
using LibSafeMath for uint256;
using LibOrder for LibOrder.Order;
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
return _batchMatchOrders(
leftOrders,
rightOrders,
leftSignatures,
rightSignatures,
false
);
}
/// @dev Match complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrdersWithMaximalFill(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
return _batchMatchOrders(
leftOrders,
rightOrders,
leftSignatures,
rightSignatures,
true
);
}
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
return _matchOrders(
leftOrder,
rightOrder,
leftSignature,
rightSignature,
false
);
}
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled by maker and taker of matched orders.
function matchOrdersWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
return _matchOrders(
leftOrder,
rightOrder,
leftSignature,
rightSignature,
true
);
}
/// @dev Validates context for matchOrders. Succeeds or throws.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftOrderHash First matched order hash.
/// @param rightOrderHash Second matched order hash.
function _assertValidMatch(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes32 leftOrderHash,
bytes32 rightOrderHash
)
internal
pure
{
// Make sure there is a profitable spread.
// There is a profitable spread iff the cost per unit bought (OrderA.MakerAmount/OrderA.TakerAmount) for each order is greater
// than the profit per unit sold of the matched order (OrderB.TakerAmount/OrderB.MakerAmount).
// This is satisfied by the equations below:
// <leftOrder.makerAssetAmount> / <leftOrder.takerAssetAmount> >= <rightOrder.takerAssetAmount> / <rightOrder.makerAssetAmount>
// AND
// <rightOrder.makerAssetAmount> / <rightOrder.takerAssetAmount> >= <leftOrder.takerAssetAmount> / <leftOrder.makerAssetAmount>
// These equations can be combined to get the following:
if (leftOrder.makerAssetAmount.safeMul(rightOrder.makerAssetAmount) <
leftOrder.takerAssetAmount.safeMul(rightOrder.takerAssetAmount)) {
LibRichErrors.rrevert(LibExchangeRichErrors.NegativeSpreadError(
leftOrderHash,
rightOrderHash
));
}
}
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// This is the reentrant version of `batchMatchOrders` and `batchMatchOrdersWithMaximalFill`.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @param shouldMaximallyFillOrders A value that indicates whether or not the order matching
/// should be done with maximal fill.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function _batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures,
bool shouldMaximallyFillOrders
)
internal
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
// Ensure that the left and right orders have nonzero lengths.
if (leftOrders.length == 0) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.ZERO_LEFT_ORDERS
));
}
if (rightOrders.length == 0) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.ZERO_RIGHT_ORDERS
));
}
// Ensure that the left and right arrays are compatible.
if (leftOrders.length != leftSignatures.length) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.INVALID_LENGTH_LEFT_SIGNATURES
));
}
if (rightOrders.length != rightSignatures.length) {
LibRichErrors.rrevert(LibExchangeRichErrors.BatchMatchOrdersError(
LibExchangeRichErrors.BatchMatchOrdersErrorCodes.INVALID_LENGTH_RIGHT_SIGNATURES
));
}
batchMatchedFillResults.left = new LibFillResults.FillResults[](leftOrders.length);
batchMatchedFillResults.right = new LibFillResults.FillResults[](rightOrders.length);
// Set up initial indices.
uint256 leftIdx = 0;
uint256 rightIdx = 0;
// Keep local variables for orders, order filled amounts, and signatures for efficiency.
LibOrder.Order memory leftOrder = leftOrders[0];
LibOrder.Order memory rightOrder = rightOrders[0];
(, uint256 leftOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(leftOrder);
(, uint256 rightOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(rightOrder);
LibFillResults.FillResults memory leftFillResults;
LibFillResults.FillResults memory rightFillResults;
// Loop infinitely (until broken inside of the loop), but keep a counter of how
// many orders have been matched.
for (;;) {
// Match the two orders that are pointed to by the left and right indices
LibFillResults.MatchedFillResults memory matchResults = _matchOrders(
leftOrder,
rightOrder,
leftSignatures[leftIdx],
rightSignatures[rightIdx],
shouldMaximallyFillOrders
);
// Update the order filled amounts with the updated takerAssetFilledAmount
leftOrderTakerAssetFilledAmount = leftOrderTakerAssetFilledAmount.safeAdd(matchResults.left.takerAssetFilledAmount);
rightOrderTakerAssetFilledAmount = rightOrderTakerAssetFilledAmount.safeAdd(matchResults.right.takerAssetFilledAmount);
// Aggregate the new fill results with the previous fill results for the current orders.
leftFillResults = LibFillResults.addFillResults(
leftFillResults,
matchResults.left
);
rightFillResults = LibFillResults.addFillResults(
rightFillResults,
matchResults.right
);
// Update the profit in the left and right maker assets using the profits from
// the match.
batchMatchedFillResults.profitInLeftMakerAsset = batchMatchedFillResults.profitInLeftMakerAsset.safeAdd(
matchResults.profitInLeftMakerAsset
);
batchMatchedFillResults.profitInRightMakerAsset = batchMatchedFillResults.profitInRightMakerAsset.safeAdd(
matchResults.profitInRightMakerAsset
);
// If the leftOrder is filled, update the leftIdx, leftOrder, and leftSignature,
// or break out of the loop if there are no more leftOrders to match.
if (leftOrderTakerAssetFilledAmount >= leftOrder.takerAssetAmount) {
// Update the batched fill results once the leftIdx is updated.
batchMatchedFillResults.left[leftIdx++] = leftFillResults;
// Clear the intermediate fill results value.
leftFillResults = LibFillResults.FillResults(0, 0, 0, 0, 0);
// If all of the left orders have been filled, break out of the loop.
// Otherwise, update the current right order.
if (leftIdx == leftOrders.length) {
// Update the right batched fill results
batchMatchedFillResults.right[rightIdx] = rightFillResults;
break;
} else {
leftOrder = leftOrders[leftIdx];
(, leftOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(leftOrder);
}
}
// If the rightOrder is filled, update the rightIdx, rightOrder, and rightSignature,
// or break out of the loop if there are no more rightOrders to match.
if (rightOrderTakerAssetFilledAmount >= rightOrder.takerAssetAmount) {
// Update the batched fill results once the rightIdx is updated.
batchMatchedFillResults.right[rightIdx++] = rightFillResults;
// Clear the intermediate fill results value.
rightFillResults = LibFillResults.FillResults(0, 0, 0, 0, 0);
// If all of the right orders have been filled, break out of the loop.
// Otherwise, update the current right order.
if (rightIdx == rightOrders.length) {
// Update the left batched fill results
batchMatchedFillResults.left[leftIdx] = leftFillResults;
break;
} else {
rightOrder = rightOrders[rightIdx];
(, rightOrderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(rightOrder);
}
}
}
// Return the fill results from the batch match
return batchMatchedFillResults;
}
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders). This
/// function is needed to allow for reentrant order matching (used by `batchMatchOrders` and
/// `batchMatchOrdersWithMaximalFill`).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @param shouldMaximallyFillOrders Indicates whether or not the maximal fill matching strategy should be used
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function _matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature,
bool shouldMaximallyFillOrders
)
internal
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
// We assume that rightOrder.takerAssetData == leftOrder.makerAssetData and rightOrder.makerAssetData == leftOrder.takerAssetData
// by pointing these values to the same location in memory. This is cheaper than checking equality.
// If this assumption isn't true, the match will fail at signature validation.
rightOrder.makerAssetData = leftOrder.takerAssetData;
rightOrder.takerAssetData = leftOrder.makerAssetData;
// Get left & right order info
LibOrder.OrderInfo memory leftOrderInfo = getOrderInfo(leftOrder);
LibOrder.OrderInfo memory rightOrderInfo = getOrderInfo(rightOrder);
// Fetch taker address
address takerAddress = _getCurrentContextAddress();
// Either our context is valid or we revert
_assertFillableOrder(
leftOrder,
leftOrderInfo,
takerAddress,
leftSignature
);
_assertFillableOrder(
rightOrder,
rightOrderInfo,
takerAddress,
rightSignature
);
_assertValidMatch(
leftOrder,
rightOrder,
leftOrderInfo.orderHash,
rightOrderInfo.orderHash
);
// Compute proportional fill amounts
matchedFillResults = LibFillResults.calculateMatchedFillResults(
leftOrder,
rightOrder,
leftOrderInfo.orderTakerAssetFilledAmount,
rightOrderInfo.orderTakerAssetFilledAmount,
protocolFeeMultiplier,
tx.gasprice,
shouldMaximallyFillOrders
);
// Update exchange state
_updateFilledState(
leftOrder,
takerAddress,
leftOrderInfo.orderHash,
leftOrderInfo.orderTakerAssetFilledAmount,
matchedFillResults.left
);
_updateFilledState(
rightOrder,
takerAddress,
rightOrderInfo.orderHash,
rightOrderInfo.orderTakerAssetFilledAmount,
matchedFillResults.right
);
// Settle matched orders. Succeeds or throws.
_settleMatchedOrders(
leftOrderInfo.orderHash,
rightOrderInfo.orderHash,
leftOrder,
rightOrder,
takerAddress,
matchedFillResults
);
return matchedFillResults;
}
/// @dev Settles matched order by transferring appropriate funds between order makers, taker, and fee recipient.
/// @param leftOrderHash First matched order hash.
/// @param rightOrderHash Second matched order hash.
/// @param leftOrder First matched order.
/// @param rightOrder Second matched order.
/// @param takerAddress Address that matched the orders. The taker receives the spread between orders as profit.
/// @param matchedFillResults Struct holding amounts to transfer between makers, taker, and fee recipients.
function _settleMatchedOrders(
bytes32 leftOrderHash,
bytes32 rightOrderHash,
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
address takerAddress,
LibFillResults.MatchedFillResults memory matchedFillResults
)
internal
{
address leftMakerAddress = leftOrder.makerAddress;
address rightMakerAddress = rightOrder.makerAddress;
address leftFeeRecipientAddress = leftOrder.feeRecipientAddress;
address rightFeeRecipientAddress = rightOrder.feeRecipientAddress;
// Right maker asset -> left maker
_dispatchTransferFrom(
rightOrderHash,
rightOrder.makerAssetData,
rightMakerAddress,
leftMakerAddress,
matchedFillResults.left.takerAssetFilledAmount
);
// Left maker asset -> right maker
_dispatchTransferFrom(
leftOrderHash,
leftOrder.makerAssetData,
leftMakerAddress,
rightMakerAddress,
matchedFillResults.right.takerAssetFilledAmount
);
// Right maker fee -> right fee recipient
_dispatchTransferFrom(
rightOrderHash,
rightOrder.makerFeeAssetData,
rightMakerAddress,
rightFeeRecipientAddress,
matchedFillResults.right.makerFeePaid
);
// Left maker fee -> left fee recipient
_dispatchTransferFrom(
leftOrderHash,
leftOrder.makerFeeAssetData,
leftMakerAddress,
leftFeeRecipientAddress,
matchedFillResults.left.makerFeePaid
);
// Settle taker profits.
_dispatchTransferFrom(
leftOrderHash,
leftOrder.makerAssetData,
leftMakerAddress,
takerAddress,
matchedFillResults.profitInLeftMakerAsset
);
_dispatchTransferFrom(
rightOrderHash,
rightOrder.makerAssetData,
rightMakerAddress,
takerAddress,
matchedFillResults.profitInRightMakerAsset
);
// Pay protocol fees for each maker
bool didPayProtocolFees = _payTwoProtocolFees(
leftOrderHash,
rightOrderHash,
matchedFillResults.left.protocolFeePaid,
leftMakerAddress,
rightMakerAddress,
takerAddress
);
// Protocol fees are not paid if the protocolFeeCollector contract is not set
if (!didPayProtocolFees) {
matchedFillResults.left.protocolFeePaid = 0;
matchedFillResults.right.protocolFeePaid = 0;
}
// Settle taker fees.
if (
leftFeeRecipientAddress == rightFeeRecipientAddress &&
leftOrder.takerFeeAssetData.equals(rightOrder.takerFeeAssetData)
) {
// Fee recipients and taker fee assets are identical, so we can
// transfer them in one go.
_dispatchTransferFrom(
leftOrderHash,
leftOrder.takerFeeAssetData,
takerAddress,
leftFeeRecipientAddress,
matchedFillResults.left.takerFeePaid.safeAdd(matchedFillResults.right.takerFeePaid)
);
} else {
// Right taker fee -> right fee recipient
_dispatchTransferFrom(
rightOrderHash,
rightOrder.takerFeeAssetData,
takerAddress,
rightFeeRecipientAddress,
matchedFillResults.right.takerFeePaid
);
// Left taker fee -> left fee recipient
_dispatchTransferFrom(
leftOrderHash,
leftOrder.takerFeeAssetData,
takerAddress,
leftFeeRecipientAddress,
matchedFillResults.left.takerFeePaid
);
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./LibBytesRichErrors.sol";
import "./LibRichErrors.sol";
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibBytesRichErrors {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
library LibOrder {
using LibOrder for Order;
// Hash for the EIP712 Order Schema:
// keccak256(abi.encodePacked(
// "Order(",
// "address makerAddress,",
// "address takerAddress,",
// "address feeRecipientAddress,",
// "address senderAddress,",
// "uint256 makerAssetAmount,",
// "uint256 takerAssetAmount,",
// "uint256 makerFee,",
// "uint256 takerFee,",
// "uint256 expirationTimeSeconds,",
// "uint256 salt,",
// "bytes makerAssetData,",
// "bytes takerAssetData,",
// "bytes makerFeeAssetData,",
// "bytes takerFeeAssetData",
// ")"
// ))
bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH =
0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534;
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's status is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// solhint-disable max-line-length
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled.
uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy.
bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy.
bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy.
}
// solhint-enable max-line-length
struct OrderInfo {
uint8 orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Calculates the EIP712 typed data hash of an order with a given domain separator.
/// @param order The order structure.
/// @return EIP712 typed data hash of the order.
function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 orderHash)
{
orderHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
order.getStructHash()
);
return orderHash;
}
/// @dev Calculates EIP712 hash of the order struct.
/// @param order The order structure.
/// @return EIP712 hash of the order struct.
function getStructHash(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH;
bytes memory makerAssetData = order.makerAssetData;
bytes memory takerAssetData = order.takerAssetData;
bytes memory makerFeeAssetData = order.makerFeeAssetData;
bytes memory takerFeeAssetData = order.takerFeeAssetData;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// uint256(order.makerAddress),
// uint256(order.takerAddress),
// uint256(order.feeRecipientAddress),
// uint256(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData),
// keccak256(order.makerFeeAssetData),
// keccak256(order.takerFeeAssetData)
// ));
assembly {
// Assert order offset (this is an internal error that should never be triggered)
if lt(order, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
let pos4 := add(order, 384)
let pos5 := add(order, 416)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
let temp4 := mload(pos4)
let temp5 := mload(pos5)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData
mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData
mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData
mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData
result := keccak256(pos1, 480)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
mstore(pos4, temp4)
mstore(pos5, temp5)
}
return result;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "./LibMath.sol";
import "./LibOrder.sol";
library LibFillResults {
using LibSafeMath for uint256;
struct BatchMatchedFillResults {
FillResults[] left; // Fill results for left orders
FillResults[] right; // Fill results for right orders
uint256 profitInLeftMakerAsset; // Profit taken from left makers
uint256 profitInRightMakerAsset; // Profit taken from right makers
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s).
uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract.
}
struct MatchedFillResults {
FillResults left; // Amounts filled and fees paid of left order.
FillResults right; // Amounts filled and fees paid of right order.
uint256 profitInLeftMakerAsset; // Profit taken from the left maker
uint256 profitInRightMakerAsset; // Profit taken from the right maker
}
/// @dev Calculates amounts filled and fees paid by maker and taker.
/// @param order to be filled.
/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults(
LibOrder.Order memory order,
uint256 takerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice
)
internal
pure
returns (FillResults memory fillResults)
{
// Compute proportional transfer amounts
fillResults.takerAssetFilledAmount = takerAssetFilledAmount;
fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerFee
);
fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.takerFee
);
// Compute the protocol fee that should be paid for a single fill.
fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier);
return fillResults;
}
/// @dev Calculates fill amounts for the matched orders.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the leftOrder order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftOrderTakerAssetFilledAmount Amount of left order already filled.
/// @param rightOrderTakerAssetFilledAmount Amount of right order already filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use
/// the maximal fill order matching strategy.
/// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders.
function calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftOrderTakerAssetFilledAmount,
uint256 rightOrderTakerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice,
bool shouldMaximallyFillOrders
)
internal
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Derive maker asset amounts for left & right orders, given store taker assert amounts
uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount);
uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
leftTakerAssetAmountRemaining
);
uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount);
uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
rightTakerAssetAmountRemaining
);
// Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets.
if (shouldMaximallyFillOrders) {
matchedFillResults = _calculateMatchedFillResultsWithMaximalFill(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else {
matchedFillResults = _calculateMatchedFillResults(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Compute fees for left order
matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.makerAssetFilledAmount,
leftOrder.makerAssetAmount,
leftOrder.makerFee
);
matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.takerAssetFilledAmount,
leftOrder.takerAssetAmount,
leftOrder.takerFee
);
// Compute fees for right order
matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.makerAssetFilledAmount,
rightOrder.makerAssetAmount,
rightOrder.makerFee
);
matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.takerAssetFilledAmount,
rightOrder.takerAssetAmount,
rightOrder.takerFee
);
// Compute the protocol fee that should be paid for a single fill. In this
// case this should be made the protocol fee for both the left and right orders.
uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier);
matchedFillResults.left.protocolFeePaid = protocolFee;
matchedFillResults.right.protocolFeePaid = protocolFee;
// Return fill results
return matchedFillResults;
}
/// @dev Adds properties of both FillResults instances.
/// @param fillResults1 The first FillResults.
/// @param fillResults2 The second FillResults.
/// @return The sum of both fill results.
function addFillResults(
FillResults memory fillResults1,
FillResults memory fillResults2
)
internal
pure
returns (FillResults memory totalFillResults)
{
totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount);
totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid);
totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid);
totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid);
return totalFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only
/// awards profit denominated in the left maker asset.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate fill results for maker and taker assets: at least one order will be fully filled.
// The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining`
// The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining`
// We have two distinct cases for calculating the fill results:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// If the left maker can buy exactly what the right maker can sell, then both orders are fully filled.
// Case 2.
// If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled.
// Case 3.
// If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round up to ensure the maker's exchange rate does not exceed the price specified by the order.
// We favor the maker when the exchange rate must be rounded.
matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil(
rightOrder.takerAssetAmount,
rightOrder.makerAssetAmount,
leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount
);
} else {
// leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining
// Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but
// this calculation will be more precise since it does not include rounding.
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
return matchedFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching
/// strategy.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResultsWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset.
bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining;
bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining;
// Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled.
//
// The maximum that the left maker can possibly buy is the amount that the right order can sell.
// The maximum that the right maker can possibly buy is the amount that the left order can sell.
//
// If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled,
// the profit will be out in the right maker asset.
//
// There are three cases to consider:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// Case 2.
// If the right maker can buy more than the left maker can sell, then only the right order is fully filled.
// Case 3.
// If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of
// what the right maker can buy, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled with the profit paid in the left makerAsset
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled with the profit paid in the right makerAsset.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round down to ensure the right maker's exchange rate does not exceed the price specified by the order.
// We favor the right maker when the exchange rate must be rounded and the profit is being paid in the
// right maker asset.
matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
leftMakerAssetAmountRemaining
);
matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining;
} else {
// Case 3: The right and left orders are fully filled
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit.
if (doesLeftMakerAssetProfitExist) {
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
}
// Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit.
if (doesRightMakerAssetProfitExist) {
matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub(
matchedFillResults.left.takerAssetFilledAmount
);
}
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order. Both orders will be fully filled in this
/// case.
/// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteFillBoth(
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate the fully filled results for both orders.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order.
/// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts
/// can be derived from this order and the right asset remaining fields.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteRightFill(
LibOrder.Order memory leftOrder,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining;
// Round down to ensure the left maker's exchange rate does not exceed the price specified by the order.
// We favor the left maker when the exchange rate must be rounded and the profit is being paid in the
// left maker asset.
matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
rightMakerAssetAmountRemaining
);
return matchedFillResults;
}
}
pragma solidity ^0.5.9;
import "./LibRichErrors.sol";
import "./LibSafeMathRichErrors.sol";
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
pragma solidity ^0.5.9;
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "./LibMathRichErrors.sol";
library LibMath {
using LibSafeMath for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
pragma solidity ^0.5.9;
library LibMathRichErrors {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "./LibOrder.sol";
library LibExchangeRichErrors {
enum AssetProxyDispatchErrorCodes {
INVALID_ASSET_DATA_LENGTH,
UNKNOWN_ASSET_PROXY
}
enum BatchMatchOrdersErrorCodes {
ZERO_LEFT_ORDERS,
ZERO_RIGHT_ORDERS,
INVALID_LENGTH_LEFT_SIGNATURES,
INVALID_LENGTH_RIGHT_SIGNATURES
}
enum ExchangeContextErrorCodes {
INVALID_MAKER,
INVALID_TAKER,
INVALID_SENDER
}
enum FillErrorCodes {
INVALID_TAKER_AMOUNT,
TAKER_OVERPAY,
OVERFILL,
INVALID_FILL_PRICE
}
enum SignatureErrorCodes {
BAD_ORDER_SIGNATURE,
BAD_TRANSACTION_SIGNATURE,
INVALID_LENGTH,
UNSUPPORTED,
ILLEGAL,
INAPPROPRIATE_SIGNATURE_TYPE,
INVALID_SIGNER
}
enum TransactionErrorCodes {
ALREADY_EXECUTED,
EXPIRED
}
enum IncompleteFillErrorCode {
INCOMPLETE_MARKET_BUY_ORDERS,
INCOMPLETE_MARKET_SELL_ORDERS,
INCOMPLETE_FILL_ORDER
}
// bytes4(keccak256("SignatureError(uint8,bytes32,address,bytes)"))
bytes4 internal constant SIGNATURE_ERROR_SELECTOR =
0x7e5a2318;
// bytes4(keccak256("SignatureValidatorNotApprovedError(address,address)"))
bytes4 internal constant SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR =
0xa15c0d06;
// bytes4(keccak256("EIP1271SignatureError(address,bytes,bytes,bytes)"))
bytes4 internal constant EIP1271_SIGNATURE_ERROR_SELECTOR =
0x5bd0428d;
// bytes4(keccak256("SignatureWalletError(bytes32,address,bytes,bytes)"))
bytes4 internal constant SIGNATURE_WALLET_ERROR_SELECTOR =
0x1b8388f7;
// bytes4(keccak256("OrderStatusError(bytes32,uint8)"))
bytes4 internal constant ORDER_STATUS_ERROR_SELECTOR =
0xfdb6ca8d;
// bytes4(keccak256("ExchangeInvalidContextError(uint8,bytes32,address)"))
bytes4 internal constant EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR =
0xe53c76c8;
// bytes4(keccak256("FillError(uint8,bytes32)"))
bytes4 internal constant FILL_ERROR_SELECTOR =
0xe94a7ed0;
// bytes4(keccak256("OrderEpochError(address,address,uint256)"))
bytes4 internal constant ORDER_EPOCH_ERROR_SELECTOR =
0x4ad31275;
// bytes4(keccak256("AssetProxyExistsError(bytes4,address)"))
bytes4 internal constant ASSET_PROXY_EXISTS_ERROR_SELECTOR =
0x11c7b720;
// bytes4(keccak256("AssetProxyDispatchError(uint8,bytes32,bytes)"))
bytes4 internal constant ASSET_PROXY_DISPATCH_ERROR_SELECTOR =
0x488219a6;
// bytes4(keccak256("AssetProxyTransferError(bytes32,bytes,bytes)"))
bytes4 internal constant ASSET_PROXY_TRANSFER_ERROR_SELECTOR =
0x4678472b;
// bytes4(keccak256("NegativeSpreadError(bytes32,bytes32)"))
bytes4 internal constant NEGATIVE_SPREAD_ERROR_SELECTOR =
0xb6555d6f;
// bytes4(keccak256("TransactionError(uint8,bytes32)"))
bytes4 internal constant TRANSACTION_ERROR_SELECTOR =
0xf5985184;
// bytes4(keccak256("TransactionExecutionError(bytes32,bytes)"))
bytes4 internal constant TRANSACTION_EXECUTION_ERROR_SELECTOR =
0x20d11f61;
// bytes4(keccak256("TransactionGasPriceError(bytes32,uint256,uint256)"))
bytes4 internal constant TRANSACTION_GAS_PRICE_ERROR_SELECTOR =
0xa26dac09;
// bytes4(keccak256("TransactionInvalidContextError(bytes32,address)"))
bytes4 internal constant TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR =
0xdec4aedf;
// bytes4(keccak256("IncompleteFillError(uint8,uint256,uint256)"))
bytes4 internal constant INCOMPLETE_FILL_ERROR_SELECTOR =
0x18e4b141;
// bytes4(keccak256("BatchMatchOrdersError(uint8)"))
bytes4 internal constant BATCH_MATCH_ORDERS_ERROR_SELECTOR =
0xd4092f4f;
// bytes4(keccak256("PayProtocolFeeError(bytes32,uint256,address,address,bytes)"))
bytes4 internal constant PAY_PROTOCOL_FEE_ERROR_SELECTOR =
0x87cb1e75;
// solhint-disable func-name-mixedcase
function SignatureErrorSelector()
internal
pure
returns (bytes4)
{
return SIGNATURE_ERROR_SELECTOR;
}
function SignatureValidatorNotApprovedErrorSelector()
internal
pure
returns (bytes4)
{
return SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR;
}
function EIP1271SignatureErrorSelector()
internal
pure
returns (bytes4)
{
return EIP1271_SIGNATURE_ERROR_SELECTOR;
}
function SignatureWalletErrorSelector()
internal
pure
returns (bytes4)
{
return SIGNATURE_WALLET_ERROR_SELECTOR;
}
function OrderStatusErrorSelector()
internal
pure
returns (bytes4)
{
return ORDER_STATUS_ERROR_SELECTOR;
}
function ExchangeInvalidContextErrorSelector()
internal
pure
returns (bytes4)
{
return EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR;
}
function FillErrorSelector()
internal
pure
returns (bytes4)
{
return FILL_ERROR_SELECTOR;
}
function OrderEpochErrorSelector()
internal
pure
returns (bytes4)
{
return ORDER_EPOCH_ERROR_SELECTOR;
}
function AssetProxyExistsErrorSelector()
internal
pure
returns (bytes4)
{
return ASSET_PROXY_EXISTS_ERROR_SELECTOR;
}
function AssetProxyDispatchErrorSelector()
internal
pure
returns (bytes4)
{
return ASSET_PROXY_DISPATCH_ERROR_SELECTOR;
}
function AssetProxyTransferErrorSelector()
internal
pure
returns (bytes4)
{
return ASSET_PROXY_TRANSFER_ERROR_SELECTOR;
}
function NegativeSpreadErrorSelector()
internal
pure
returns (bytes4)
{
return NEGATIVE_SPREAD_ERROR_SELECTOR;
}
function TransactionErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_ERROR_SELECTOR;
}
function TransactionExecutionErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_EXECUTION_ERROR_SELECTOR;
}
function IncompleteFillErrorSelector()
internal
pure
returns (bytes4)
{
return INCOMPLETE_FILL_ERROR_SELECTOR;
}
function BatchMatchOrdersErrorSelector()
internal
pure
returns (bytes4)
{
return BATCH_MATCH_ORDERS_ERROR_SELECTOR;
}
function TransactionGasPriceErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_GAS_PRICE_ERROR_SELECTOR;
}
function TransactionInvalidContextErrorSelector()
internal
pure
returns (bytes4)
{
return TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR;
}
function PayProtocolFeeErrorSelector()
internal
pure
returns (bytes4)
{
return PAY_PROTOCOL_FEE_ERROR_SELECTOR;
}
function BatchMatchOrdersError(
BatchMatchOrdersErrorCodes errorCode
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
BATCH_MATCH_ORDERS_ERROR_SELECTOR,
errorCode
);
}
function SignatureError(
SignatureErrorCodes errorCode,
bytes32 hash,
address signerAddress,
bytes memory signature
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SIGNATURE_ERROR_SELECTOR,
errorCode,
hash,
signerAddress,
signature
);
}
function SignatureValidatorNotApprovedError(
address signerAddress,
address validatorAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SIGNATURE_VALIDATOR_NOT_APPROVED_ERROR_SELECTOR,
signerAddress,
validatorAddress
);
}
function EIP1271SignatureError(
address verifyingContractAddress,
bytes memory data,
bytes memory signature,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
EIP1271_SIGNATURE_ERROR_SELECTOR,
verifyingContractAddress,
data,
signature,
errorData
);
}
function SignatureWalletError(
bytes32 hash,
address walletAddress,
bytes memory signature,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SIGNATURE_WALLET_ERROR_SELECTOR,
hash,
walletAddress,
signature,
errorData
);
}
function OrderStatusError(
bytes32 orderHash,
LibOrder.OrderStatus orderStatus
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ORDER_STATUS_ERROR_SELECTOR,
orderHash,
orderStatus
);
}
function ExchangeInvalidContextError(
ExchangeContextErrorCodes errorCode,
bytes32 orderHash,
address contextAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
EXCHANGE_INVALID_CONTEXT_ERROR_SELECTOR,
errorCode,
orderHash,
contextAddress
);
}
function FillError(
FillErrorCodes errorCode,
bytes32 orderHash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
FILL_ERROR_SELECTOR,
errorCode,
orderHash
);
}
function OrderEpochError(
address makerAddress,
address orderSenderAddress,
uint256 currentEpoch
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ORDER_EPOCH_ERROR_SELECTOR,
makerAddress,
orderSenderAddress,
currentEpoch
);
}
function AssetProxyExistsError(
bytes4 assetProxyId,
address assetProxyAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ASSET_PROXY_EXISTS_ERROR_SELECTOR,
assetProxyId,
assetProxyAddress
);
}
function AssetProxyDispatchError(
AssetProxyDispatchErrorCodes errorCode,
bytes32 orderHash,
bytes memory assetData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ASSET_PROXY_DISPATCH_ERROR_SELECTOR,
errorCode,
orderHash,
assetData
);
}
function AssetProxyTransferError(
bytes32 orderHash,
bytes memory assetData,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ASSET_PROXY_TRANSFER_ERROR_SELECTOR,
orderHash,
assetData,
errorData
);
}
function NegativeSpreadError(
bytes32 leftOrderHash,
bytes32 rightOrderHash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
NEGATIVE_SPREAD_ERROR_SELECTOR,
leftOrderHash,
rightOrderHash
);
}
function TransactionError(
TransactionErrorCodes errorCode,
bytes32 transactionHash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_ERROR_SELECTOR,
errorCode,
transactionHash
);
}
function TransactionExecutionError(
bytes32 transactionHash,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_EXECUTION_ERROR_SELECTOR,
transactionHash,
errorData
);
}
function TransactionGasPriceError(
bytes32 transactionHash,
uint256 actualGasPrice,
uint256 requiredGasPrice
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_GAS_PRICE_ERROR_SELECTOR,
transactionHash,
actualGasPrice,
requiredGasPrice
);
}
function TransactionInvalidContextError(
bytes32 transactionHash,
address currentContextAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TRANSACTION_INVALID_CONTEXT_ERROR_SELECTOR,
transactionHash,
currentContextAddress
);
}
function IncompleteFillError(
IncompleteFillErrorCode errorCode,
uint256 expectedAssetFillAmount,
uint256 actualAssetFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INCOMPLETE_FILL_ERROR_SELECTOR,
errorCode,
expectedAssetFillAmount,
actualAssetFillAmount
);
}
function PayProtocolFeeError(
bytes32 orderHash,
uint256 protocolFee,
address makerAddress,
address takerAddress,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
PAY_PROTOCOL_FEE_ERROR_SELECTOR,
orderHash,
protocolFee,
makerAddress,
takerAddress,
errorData
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
contract IMatchOrders {
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrdersWithMaximalFill(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled by maker and taker of matched orders.
function matchOrdersWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-utils/contracts/src/Refundable.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IExchangeCore.sol";
import "./MixinAssetProxyDispatcher.sol";
import "./MixinProtocolFees.sol";
import "./MixinSignatureValidator.sol";
contract MixinExchangeCore is
IExchangeCore,
Refundable,
LibEIP712ExchangeDomain,
MixinAssetProxyDispatcher,
MixinProtocolFees,
MixinSignatureValidator
{
using LibOrder for LibOrder.Order;
using LibSafeMath for uint256;
using LibBytes for bytes;
// Mapping of orderHash => amount of takerAsset already bought by maker
mapping (bytes32 => uint256) public filled;
// Mapping of orderHash => cancelled
mapping (bytes32 => bool) public cancelled;
// Mapping of makerAddress => senderAddress => lowest salt an order can have in order to be fillable
// Orders with specified senderAddress and with a salt less than their epoch are considered cancelled
mapping (address => mapping (address => uint256)) public orderEpoch;
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external
payable
refundFinalBalanceNoReentry
{
address makerAddress = _getCurrentContextAddress();
// If this function is called via `executeTransaction`, we only update the orderEpoch for the makerAddress/msg.sender combination.
// This allows external filter contracts to add rules to how orders are cancelled via this function.
address orderSenderAddress = makerAddress == msg.sender ? address(0) : msg.sender;
// orderEpoch is initialized to 0, so to cancelUpTo we need salt + 1
uint256 newOrderEpoch = targetOrderEpoch + 1;
uint256 oldOrderEpoch = orderEpoch[makerAddress][orderSenderAddress];
// Ensure orderEpoch is monotonically increasing
if (newOrderEpoch <= oldOrderEpoch) {
LibRichErrors.rrevert(LibExchangeRichErrors.OrderEpochError(
makerAddress,
orderSenderAddress,
oldOrderEpoch
));
}
// Update orderEpoch
orderEpoch[makerAddress][orderSenderAddress] = newOrderEpoch;
emit CancelUpTo(
makerAddress,
orderSenderAddress,
newOrderEpoch
);
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = _fillOrder(
order,
takerAssetFillAmount,
signature
);
return fillResults;
}
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public
payable
refundFinalBalanceNoReentry
{
_cancelOrder(order);
}
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo)
{
// Compute the order hash and fetch the amount of takerAsset that has already been filled
(orderInfo.orderHash, orderInfo.orderTakerAssetFilledAmount) = _getOrderHashAndFilledAmount(order);
// If order.makerAssetAmount is zero, we also reject the order.
// While the Exchange contract handles them correctly, they create
// edge cases in the supporting infrastructure because they have
// an 'infinite' price when computed by a simple division.
if (order.makerAssetAmount == 0) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.INVALID_MAKER_ASSET_AMOUNT);
return orderInfo;
}
// If order.takerAssetAmount is zero, then the order will always
// be considered filled because 0 == takerAssetAmount == orderTakerAssetFilledAmount
// Instead of distinguishing between unfilled and filled zero taker
// amount orders, we choose not to support them.
if (order.takerAssetAmount == 0) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.INVALID_TAKER_ASSET_AMOUNT);
return orderInfo;
}
// Validate order availability
if (orderInfo.orderTakerAssetFilledAmount >= order.takerAssetAmount) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.FULLY_FILLED);
return orderInfo;
}
// Validate order expiration
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= order.expirationTimeSeconds) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.EXPIRED);
return orderInfo;
}
// Check if order has been cancelled
if (cancelled[orderInfo.orderHash]) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.CANCELLED);
return orderInfo;
}
if (orderEpoch[order.makerAddress][order.senderAddress] > order.salt) {
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.CANCELLED);
return orderInfo;
}
// All other statuses are ruled out: order is Fillable
orderInfo.orderStatus = uint8(LibOrder.OrderStatus.FILLABLE);
return orderInfo;
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function _fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// Fetch order info
LibOrder.OrderInfo memory orderInfo = getOrderInfo(order);
// Fetch taker address
address takerAddress = _getCurrentContextAddress();
// Assert that the order is fillable by taker
_assertFillableOrder(
order,
orderInfo,
takerAddress,
signature
);
// Get amount of takerAsset to fill
uint256 remainingTakerAssetAmount = order.takerAssetAmount.safeSub(orderInfo.orderTakerAssetFilledAmount);
uint256 takerAssetFilledAmount = LibSafeMath.min256(takerAssetFillAmount, remainingTakerAssetAmount);
// Compute proportional fill amounts
fillResults = LibFillResults.calculateFillResults(
order,
takerAssetFilledAmount,
protocolFeeMultiplier,
tx.gasprice
);
bytes32 orderHash = orderInfo.orderHash;
// Update exchange internal state
_updateFilledState(
order,
takerAddress,
orderHash,
orderInfo.orderTakerAssetFilledAmount,
fillResults
);
// Settle order
_settleOrder(
orderHash,
order,
takerAddress,
fillResults
);
return fillResults;
}
/// @dev After calling, the order can not be filled anymore.
/// Throws if order is invalid or sender does not have permission to cancel.
/// @param order Order to cancel. Order must be OrderStatus.FILLABLE.
function _cancelOrder(LibOrder.Order memory order)
internal
{
// Fetch current order status
LibOrder.OrderInfo memory orderInfo = getOrderInfo(order);
// Validate context
_assertValidCancel(order, orderInfo);
// Noop if order is already unfillable
if (orderInfo.orderStatus != uint8(LibOrder.OrderStatus.FILLABLE)) {
return;
}
// Perform cancel
_updateCancelledState(order, orderInfo.orderHash);
}
/// @dev Updates state with results of a fill order.
/// @param order that was filled.
/// @param takerAddress Address of taker who filled the order.
/// @param orderTakerAssetFilledAmount Amount of order already filled.
function _updateFilledState(
LibOrder.Order memory order,
address takerAddress,
bytes32 orderHash,
uint256 orderTakerAssetFilledAmount,
LibFillResults.FillResults memory fillResults
)
internal
{
// Update state
filled[orderHash] = orderTakerAssetFilledAmount.safeAdd(fillResults.takerAssetFilledAmount);
emit Fill(
order.makerAddress,
order.feeRecipientAddress,
order.makerAssetData,
order.takerAssetData,
order.makerFeeAssetData,
order.takerFeeAssetData,
orderHash,
takerAddress,
msg.sender,
fillResults.makerAssetFilledAmount,
fillResults.takerAssetFilledAmount,
fillResults.makerFeePaid,
fillResults.takerFeePaid,
fillResults.protocolFeePaid
);
}
/// @dev Updates state with results of cancelling an order.
/// State is only updated if the order is currently fillable.
/// Otherwise, updating state would have no effect.
/// @param order that was cancelled.
/// @param orderHash Hash of order that was cancelled.
function _updateCancelledState(
LibOrder.Order memory order,
bytes32 orderHash
)
internal
{
// Perform cancel
cancelled[orderHash] = true;
// Log cancel
emit Cancel(
order.makerAddress,
order.feeRecipientAddress,
order.makerAssetData,
order.takerAssetData,
msg.sender,
orderHash
);
}
/// @dev Validates context for fillOrder. Succeeds or throws.
/// @param order to be filled.
/// @param orderInfo OrderStatus, orderHash, and amount already filled of order.
/// @param takerAddress Address of order taker.
/// @param signature Proof that the orders was created by its maker.
function _assertFillableOrder(
LibOrder.Order memory order,
LibOrder.OrderInfo memory orderInfo,
address takerAddress,
bytes memory signature
)
internal
view
{
// An order can only be filled if its status is FILLABLE.
if (orderInfo.orderStatus != uint8(LibOrder.OrderStatus.FILLABLE)) {
LibRichErrors.rrevert(LibExchangeRichErrors.OrderStatusError(
orderInfo.orderHash,
LibOrder.OrderStatus(orderInfo.orderStatus)
));
}
// Validate sender is allowed to fill this order
if (order.senderAddress != address(0)) {
if (order.senderAddress != msg.sender) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_SENDER,
orderInfo.orderHash,
msg.sender
));
}
}
// Validate taker is allowed to fill this order
if (order.takerAddress != address(0)) {
if (order.takerAddress != takerAddress) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_TAKER,
orderInfo.orderHash,
takerAddress
));
}
}
// Validate signature
if (!_isValidOrderWithHashSignature(
order,
orderInfo.orderHash,
signature
)
) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.BAD_ORDER_SIGNATURE,
orderInfo.orderHash,
order.makerAddress,
signature
));
}
}
/// @dev Validates context for cancelOrder. Succeeds or throws.
/// @param order to be cancelled.
/// @param orderInfo OrderStatus, orderHash, and amount already filled of order.
function _assertValidCancel(
LibOrder.Order memory order,
LibOrder.OrderInfo memory orderInfo
)
internal
view
{
// Validate sender is allowed to cancel this order
if (order.senderAddress != address(0)) {
if (order.senderAddress != msg.sender) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_SENDER,
orderInfo.orderHash,
msg.sender
));
}
}
// Validate transaction signed by maker
address makerAddress = _getCurrentContextAddress();
if (order.makerAddress != makerAddress) {
LibRichErrors.rrevert(LibExchangeRichErrors.ExchangeInvalidContextError(
LibExchangeRichErrors.ExchangeContextErrorCodes.INVALID_MAKER,
orderInfo.orderHash,
makerAddress
));
}
}
/// @dev Settles an order by transferring assets between counterparties.
/// @param orderHash The order hash.
/// @param order Order struct containing order specifications.
/// @param takerAddress Address selling takerAsset and buying makerAsset.
/// @param fillResults Amounts to be filled and fees paid by maker and taker.
function _settleOrder(
bytes32 orderHash,
LibOrder.Order memory order,
address takerAddress,
LibFillResults.FillResults memory fillResults
)
internal
{
// Transfer taker -> maker
_dispatchTransferFrom(
orderHash,
order.takerAssetData,
takerAddress,
order.makerAddress,
fillResults.takerAssetFilledAmount
);
// Transfer maker -> taker
_dispatchTransferFrom(
orderHash,
order.makerAssetData,
order.makerAddress,
takerAddress,
fillResults.makerAssetFilledAmount
);
// Transfer taker fee -> feeRecipient
_dispatchTransferFrom(
orderHash,
order.takerFeeAssetData,
takerAddress,
order.feeRecipientAddress,
fillResults.takerFeePaid
);
// Transfer maker fee -> feeRecipient
_dispatchTransferFrom(
orderHash,
order.makerFeeAssetData,
order.makerAddress,
order.feeRecipientAddress,
fillResults.makerFeePaid
);
// Pay protocol fee
bool didPayProtocolFee = _paySingleProtocolFee(
orderHash,
fillResults.protocolFeePaid,
order.makerAddress,
takerAddress
);
// Protocol fees are not paid if the protocolFeeCollector contract is not set
if (!didPayProtocolFee) {
fillResults.protocolFeePaid = 0;
}
}
/// @dev Gets the order's hash and amount of takerAsset that has already been filled.
/// @param order Order struct containing order specifications.
/// @return The typed data hash and amount filled of the order.
function _getOrderHashAndFilledAmount(LibOrder.Order memory order)
internal
view
returns (bytes32 orderHash, uint256 orderTakerAssetFilledAmount)
{
orderHash = order.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
orderTakerAssetFilledAmount = filled[orderHash];
return (orderHash, orderTakerAssetFilledAmount);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./ReentrancyGuard.sol";
contract Refundable is
ReentrancyGuard
{
// This bool is used by the refund modifier to allow for lazily evaluated refunds.
bool internal _shouldNotRefund;
modifier refundFinalBalance {
_;
_refundNonZeroBalanceIfEnabled();
}
modifier refundFinalBalanceNoReentry {
_lockMutexOrThrowIfAlreadyLocked();
_;
_refundNonZeroBalanceIfEnabled();
_unlockMutex();
}
modifier disableRefundUntilEnd {
if (_areRefundsDisabled()) {
_;
} else {
_disableRefund();
_;
_enableAndRefundNonZeroBalance();
}
}
function _refundNonZeroBalanceIfEnabled()
internal
{
if (!_areRefundsDisabled()) {
_refundNonZeroBalance();
}
}
function _refundNonZeroBalance()
internal
{
uint256 balance = address(this).balance;
if (balance > 0) {
msg.sender.transfer(balance);
}
}
function _disableRefund()
internal
{
_shouldNotRefund = true;
}
function _enableAndRefundNonZeroBalance()
internal
{
_shouldNotRefund = false;
_refundNonZeroBalance();
}
function _areRefundsDisabled()
internal
view
returns (bool)
{
return _shouldNotRefund;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./LibReentrancyGuardRichErrors.sol";
import "./LibRichErrors.sol";
contract ReentrancyGuard {
// Locked state of mutex.
bool private _locked = false;
/// @dev Functions with this modifer cannot be reentered. The mutex will be locked
/// before function execution and unlocked after.
modifier nonReentrant() {
_lockMutexOrThrowIfAlreadyLocked();
_;
_unlockMutex();
}
function _lockMutexOrThrowIfAlreadyLocked()
internal
{
// Ensure mutex is unlocked.
if (_locked) {
LibRichErrors.rrevert(
LibReentrancyGuardRichErrors.IllegalReentrancyError()
);
}
// Lock mutex.
_locked = true;
}
function _unlockMutex()
internal
{
// Unlock mutex.
_locked = false;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibReentrancyGuardRichErrors {
// bytes4(keccak256("IllegalReentrancyError()"))
bytes internal constant ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES =
hex"0c3b823f";
// solhint-disable func-name-mixedcase
function IllegalReentrancyError()
internal
pure
returns (bytes memory)
{
return ILLEGAL_REENTRANCY_ERROR_SELECTOR_BYTES;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
contract IExchangeCore {
// Fill event is emitted whenever an order is filled.
event Fill(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that received fees.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset.
bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset.
bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash).
address takerAddress, // Address that filled the order.
address senderAddress, // Address that called the Exchange contract (msg.sender).
uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker.
uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker.
uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker.
uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker.
uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract.
);
// Cancel event is emitted whenever an individual order is cancelled.
event Cancel(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
address senderAddress, // Address that called the Exchange contract (msg.sender).
bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash).
);
// CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully.
event CancelUpTo(
address indexed makerAddress, // Orders cancelled must have been created by this address.
address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address.
uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled.
);
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external
payable;
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public
payable;
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IAssetProxy.sol";
import "./interfaces/IAssetProxyDispatcher.sol";
contract MixinAssetProxyDispatcher is
Ownable,
IAssetProxyDispatcher
{
using LibBytes for bytes;
// Mapping from Asset Proxy Id's to their respective Asset Proxy
mapping (bytes4 => address) internal _assetProxies;
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external
onlyOwner
{
// Ensure that no asset proxy exists with current id.
bytes4 assetProxyId = IAssetProxy(assetProxy).getProxyId();
address currentAssetProxy = _assetProxies[assetProxyId];
if (currentAssetProxy != address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyExistsError(
assetProxyId,
currentAssetProxy
));
}
// Add asset proxy and log registration.
_assetProxies[assetProxyId] = assetProxy;
emit AssetProxyRegistered(
assetProxyId,
assetProxy
);
}
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address)
{
return _assetProxies[assetProxyId];
}
/// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws.
/// @param orderHash Hash of the order associated with this transfer.
/// @param assetData Byte array encoded for the asset.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param amount Amount of token to transfer.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
// Do nothing if no amount should be transferred.
if (amount > 0) {
// Ensure assetData is padded to 32 bytes (excluding the id) and is at least 4 bytes long
if (assetData.length % 32 != 4) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyDispatchError(
LibExchangeRichErrors.AssetProxyDispatchErrorCodes.INVALID_ASSET_DATA_LENGTH,
orderHash,
assetData
));
}
// Lookup assetProxy.
bytes4 assetProxyId = assetData.readBytes4(0);
address assetProxy = _assetProxies[assetProxyId];
// Ensure that assetProxy exists
if (assetProxy == address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyDispatchError(
LibExchangeRichErrors.AssetProxyDispatchErrorCodes.UNKNOWN_ASSET_PROXY,
orderHash,
assetData
));
}
// Construct the calldata for the transferFrom call.
bytes memory proxyCalldata = abi.encodeWithSelector(
IAssetProxy(address(0)).transferFrom.selector,
assetData,
from,
to,
amount
);
// Call the asset proxy's transferFrom function with the constructed calldata.
(bool didSucceed, bytes memory returnData) = assetProxy.call(proxyCalldata);
// If the transaction did not succeed, revert with the returned data.
if (!didSucceed) {
LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyTransferError(
orderHash,
assetData,
returnData
));
}
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./interfaces/IOwnable.sol";
import "./LibOwnableRichErrors.sol";
import "./LibRichErrors.sol";
contract Ownable is
IOwnable
{
address public owner;
constructor ()
public
{
owner = msg.sender;
}
modifier onlyOwner() {
_assertSenderIsOwner();
_;
}
function transferOwnership(address newOwner)
public
onlyOwner
{
if (newOwner == address(0)) {
LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError());
} else {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
function _assertSenderIsOwner()
internal
view
{
if (msg.sender != owner) {
LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError(
msg.sender,
owner
));
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IOwnable {
/// @dev Emitted by Ownable when ownership is transferred.
/// @param previousOwner The previous owner of the contract.
/// @param newOwner The new owner of the contract.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev Transfers ownership of the contract to a new address.
/// @param newOwner The address that will become the owner.
function transferOwnership(address newOwner)
public;
}
pragma solidity ^0.5.9;
library LibOwnableRichErrors {
// bytes4(keccak256("OnlyOwnerError(address,address)"))
bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR =
0x1de45ad1;
// bytes4(keccak256("TransferOwnerToZeroError()"))
bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES =
hex"e69edc3e";
// solhint-disable func-name-mixedcase
function OnlyOwnerError(
address sender,
address owner
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ONLY_OWNER_ERROR_SELECTOR,
sender,
owner
);
}
function TransferOwnerToZeroError()
internal
pure
returns (bytes memory)
{
return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IAssetProxy {
/// @dev Transfers assets. Either succeeds or throws.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer.
function transferFrom(
bytes calldata assetData,
address from,
address to,
uint256 amount
)
external;
/// @dev Gets the proxy id associated with the proxy address.
/// @return Proxy id.
function getProxyId()
external
pure
returns (bytes4);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IAssetProxyDispatcher {
// Logs registration of new asset proxy
event AssetProxyRegistered(
bytes4 id, // Id of new registered AssetProxy.
address assetProxy // Address of new registered AssetProxy.
);
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/Ownable.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "@0x/contracts-staking/contracts/src/interfaces/IStaking.sol";
import "./interfaces/IProtocolFees.sol";
contract MixinProtocolFees is
IProtocolFees,
Ownable
{
// The protocol fee multiplier -- the owner can update this field.
uint256 public protocolFeeMultiplier;
// The address of the registered protocolFeeCollector contract -- the owner can update this field.
address public protocolFeeCollector;
/// @dev Allows the owner to update the protocol fee multiplier.
/// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier.
function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier)
external
onlyOwner
{
emit ProtocolFeeMultiplier(protocolFeeMultiplier, updatedProtocolFeeMultiplier);
protocolFeeMultiplier = updatedProtocolFeeMultiplier;
}
/// @dev Allows the owner to update the protocolFeeCollector address.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
external
onlyOwner
{
_setProtocolFeeCollectorAddress(updatedProtocolFeeCollector);
}
/// @dev Sets the protocolFeeCollector contract address to 0.
/// Only callable by owner.
function detachProtocolFeeCollector()
external
onlyOwner
{
_setProtocolFeeCollectorAddress(address(0));
}
/// @dev Sets the protocolFeeCollector address and emits an event.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function _setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
internal
{
emit ProtocolFeeCollectorAddress(protocolFeeCollector, updatedProtocolFeeCollector);
protocolFeeCollector = updatedProtocolFeeCollector;
}
/// @dev Pays a protocol fee for a single fill.
/// @param orderHash Hash of the order being filled.
/// @param protocolFee Value of the fee being paid (equal to protocolFeeMultiplier * tx.gasPrice).
/// @param makerAddress Address of maker of order being filled.
/// @param takerAddress Address filling order.
function _paySingleProtocolFee(
bytes32 orderHash,
uint256 protocolFee,
address makerAddress,
address takerAddress
)
internal
returns (bool)
{
address feeCollector = protocolFeeCollector;
if (feeCollector != address(0)) {
_payProtocolFeeToFeeCollector(
orderHash,
feeCollector,
address(this).balance,
protocolFee,
makerAddress,
takerAddress
);
return true;
} else {
return false;
}
}
/// @dev Pays a protocol fee for two orders (used when settling functions in MixinMatchOrders)
/// @param orderHash1 Hash of the first order being filled.
/// @param orderHash2 Hash of the second order being filled.
/// @param protocolFee Value of the fee being paid (equal to protocolFeeMultiplier * tx.gasPrice).
/// @param makerAddress1 Address of maker of first order being filled.
/// @param makerAddress2 Address of maker of second order being filled.
/// @param takerAddress Address filling orders.
function _payTwoProtocolFees(
bytes32 orderHash1,
bytes32 orderHash2,
uint256 protocolFee,
address makerAddress1,
address makerAddress2,
address takerAddress
)
internal
returns (bool)
{
address feeCollector = protocolFeeCollector;
if (feeCollector != address(0)) {
// Since the `BALANCE` opcode costs 400 gas, we choose to calculate this value by hand rather than calling it twice.
uint256 exchangeBalance = address(this).balance;
// Pay protocol fee and attribute to first maker
uint256 valuePaid = _payProtocolFeeToFeeCollector(
orderHash1,
feeCollector,
exchangeBalance,
protocolFee,
makerAddress1,
takerAddress
);
// Pay protocol fee and attribute to second maker
_payProtocolFeeToFeeCollector(
orderHash2,
feeCollector,
exchangeBalance - valuePaid,
protocolFee,
makerAddress2,
takerAddress
);
return true;
} else {
return false;
}
}
/// @dev Pays a single protocol fee.
/// @param orderHash Hash of the order being filled.
/// @param feeCollector Address of protocolFeeCollector contract.
/// @param exchangeBalance Assumed ETH balance of Exchange contract (in wei).
/// @param protocolFee Value of the fee being paid (equal to protocolFeeMultiplier * tx.gasPrice).
/// @param makerAddress Address of maker of order being filled.
/// @param takerAddress Address filling order.
function _payProtocolFeeToFeeCollector(
bytes32 orderHash,
address feeCollector,
uint256 exchangeBalance,
uint256 protocolFee,
address makerAddress,
address takerAddress
)
internal
returns (uint256 valuePaid)
{
// Do not send a value with the call if the exchange has an insufficient balance
// The protocolFeeCollector contract will fallback to charging WETH
if (exchangeBalance >= protocolFee) {
valuePaid = protocolFee;
}
bytes memory payProtocolFeeData = abi.encodeWithSelector(
IStaking(address(0)).payProtocolFee.selector,
makerAddress,
takerAddress,
protocolFee
);
// solhint-disable-next-line avoid-call-value
(bool didSucceed, bytes memory returnData) = feeCollector.call.value(valuePaid)(payProtocolFeeData);
if (!didSucceed) {
LibRichErrors.rrevert(LibExchangeRichErrors.PayProtocolFeeError(
orderHash,
protocolFee,
makerAddress,
takerAddress,
returnData
));
}
return valuePaid;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
import "./IStructs.sol";
import "./IZrxVault.sol";
interface IStaking {
/// @dev Adds a new exchange address
/// @param addr Address of exchange contract to add
function addExchangeAddress(address addr)
external;
/// @dev Create a new staking pool. The sender will be the operator of this pool.
/// Note that an operator must be payable.
/// @param operatorShare Portion of rewards owned by the operator, in ppm.
/// @param addOperatorAsMaker Adds operator to the created pool as a maker for convenience iff true.
/// @return poolId The unique pool id generated for this pool.
function createStakingPool(uint32 operatorShare, bool addOperatorAsMaker)
external
returns (bytes32 poolId);
/// @dev Decreases the operator share for the given pool (i.e. increases pool rewards for members).
/// @param poolId Unique Id of pool.
/// @param newOperatorShare The newly decreased percentage of any rewards owned by the operator.
function decreaseStakingPoolOperatorShare(bytes32 poolId, uint32 newOperatorShare)
external;
/// @dev Begins a new epoch, preparing the prior one for finalization.
/// Throws if not enough time has passed between epochs or if the
/// previous epoch was not fully finalized.
/// @return numPoolsToFinalize The number of unfinalized pools.
function endEpoch()
external
returns (uint256);
/// @dev Instantly finalizes a single pool that earned rewards in the previous
/// epoch, crediting it rewards for members and withdrawing operator's
/// rewards as WETH. This can be called by internal functions that need
/// to finalize a pool immediately. Does nothing if the pool is already
/// finalized or did not earn rewards in the previous epoch.
/// @param poolId The pool ID to finalize.
function finalizePool(bytes32 poolId)
external;
/// @dev Initialize storage owned by this contract.
/// This function should not be called directly.
/// The StakingProxy contract will call it in `attachStakingContract()`.
function init()
external;
/// @dev Allows caller to join a staking pool as a maker.
/// @param poolId Unique id of pool.
function joinStakingPoolAsMaker(bytes32 poolId)
external;
/// @dev Moves stake between statuses: 'undelegated' or 'delegated'.
/// Delegated stake can also be moved between pools.
/// This change comes into effect next epoch.
/// @param from status to move stake out of.
/// @param to status to move stake into.
/// @param amount of stake to move.
function moveStake(
IStructs.StakeInfo calldata from,
IStructs.StakeInfo calldata to,
uint256 amount
)
external;
/// @dev Pays a protocol fee in ETH.
/// @param makerAddress The address of the order's maker.
/// @param payerAddress The address that is responsible for paying the protocol fee.
/// @param protocolFee The amount of protocol fees that should be paid.
function payProtocolFee(
address makerAddress,
address payerAddress,
uint256 protocolFee
)
external
payable;
/// @dev Removes an existing exchange address
/// @param addr Address of exchange contract to remove
function removeExchangeAddress(address addr)
external;
/// @dev Set all configurable parameters at once.
/// @param _epochDurationInSeconds Minimum seconds between epochs.
/// @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
/// @param _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
/// @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
/// @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
function setParams(
uint256 _epochDurationInSeconds,
uint32 _rewardDelegatedStakeWeight,
uint256 _minimumPoolStake,
uint32 _cobbDouglasAlphaNumerator,
uint32 _cobbDouglasAlphaDenominator
)
external;
/// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault.
/// Unstake to retrieve the ZRX. Stake is in the 'Active' status.
/// @param amount of ZRX to stake.
function stake(uint256 amount)
external;
/// @dev Unstake. Tokens are withdrawn from the ZRX Vault and returned to
/// the staker. Stake must be in the 'undelegated' status in both the
/// current and next epoch in order to be unstaked.
/// @param amount of ZRX to unstake.
function unstake(uint256 amount)
external;
/// @dev Withdraws the caller's WETH rewards that have accumulated
/// until the last epoch.
/// @param poolId Unique id of pool.
function withdrawDelegatorRewards(bytes32 poolId)
external;
/// @dev Computes the reward balance in ETH of a specific member of a pool.
/// @param poolId Unique id of pool.
/// @param member The member of the pool.
/// @return totalReward Balance in ETH.
function computeRewardBalanceOfDelegator(bytes32 poolId, address member)
external
view
returns (uint256 reward);
/// @dev Computes the reward balance in ETH of the operator of a pool.
/// @param poolId Unique id of pool.
/// @return totalReward Balance in ETH.
function computeRewardBalanceOfOperator(bytes32 poolId)
external
view
returns (uint256 reward);
/// @dev Returns the earliest end time in seconds of this epoch.
/// The next epoch can begin once this time is reached.
/// Epoch period = [startTimeInSeconds..endTimeInSeconds)
/// @return Time in seconds.
function getCurrentEpochEarliestEndTimeInSeconds()
external
view
returns (uint256);
/// @dev Gets global stake for a given status.
/// @param stakeStatus UNDELEGATED or DELEGATED
/// @return Global stake for given status.
function getGlobalStakeByStatus(IStructs.StakeStatus stakeStatus)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev Gets an owner's stake balances by status.
/// @param staker Owner of stake.
/// @param stakeStatus UNDELEGATED or DELEGATED
/// @return Owner's stake balances for given status.
function getOwnerStakeByStatus(
address staker,
IStructs.StakeStatus stakeStatus
)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev Retrieves all configurable parameter values.
/// @return _epochDurationInSeconds Minimum seconds between epochs.
/// @return _rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm.
/// @return _minimumPoolStake Minimum amount of stake required in a pool to collect rewards.
/// @return _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor.
/// @return _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor.
function getParams()
external
view
returns (
uint256 _epochDurationInSeconds,
uint32 _rewardDelegatedStakeWeight,
uint256 _minimumPoolStake,
uint32 _cobbDouglasAlphaNumerator,
uint32 _cobbDouglasAlphaDenominator
);
/// @param staker of stake.
/// @param poolId Unique Id of pool.
/// @return Stake delegated to pool by staker.
function getStakeDelegatedToPoolByOwner(address staker, bytes32 poolId)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev Returns a staking pool
/// @param poolId Unique id of pool.
function getStakingPool(bytes32 poolId)
external
view
returns (IStructs.Pool memory);
/// @dev Get stats on a staking pool in this epoch.
/// @param poolId Pool Id to query.
/// @return PoolStats struct for pool id.
function getStakingPoolStatsThisEpoch(bytes32 poolId)
external
view
returns (IStructs.PoolStats memory);
/// @dev Returns the total stake delegated to a specific staking pool,
/// across all members.
/// @param poolId Unique Id of pool.
/// @return Total stake delegated to pool.
function getTotalStakeDelegatedToPool(bytes32 poolId)
external
view
returns (IStructs.StoredBalance memory balance);
/// @dev An overridable way to access the deployed WETH contract.
/// Must be view to allow overrides to access state.
/// @return wethContract The WETH contract instance.
function getWethContract()
external
view
returns (IEtherToken wethContract);
/// @dev An overridable way to access the deployed zrxVault.
/// Must be view to allow overrides to access state.
/// @return zrxVault The zrxVault contract.
function getZrxVault()
external
view
returns (IZrxVault zrxVault);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "./IERC20Token.sol";
contract IEtherToken is
IERC20Token
{
function deposit()
public
payable;
function withdraw(uint256 amount)
public;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IERC20Token {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
external
view
returns (uint256);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
interface IStructs {
/// @dev Stats for a pool that earned rewards.
/// @param feesCollected Fees collected in ETH by this pool.
/// @param weightedStake Amount of weighted stake in the pool.
/// @param membersStake Amount of non-operator stake in the pool.
struct PoolStats {
uint256 feesCollected;
uint256 weightedStake;
uint256 membersStake;
}
/// @dev Holds stats aggregated across a set of pools.
/// @param rewardsAvailable Rewards (ETH) available to the epoch
/// being finalized (the previous epoch). This is simply the balance
/// of the contract at the end of the epoch.
/// @param numPoolsToFinalize The number of pools that have yet to be finalized through `finalizePools()`.
/// @param totalFeesCollected The total fees collected for the epoch being finalized.
/// @param totalWeightedStake The total fees collected for the epoch being finalized.
/// @param totalRewardsFinalized Amount of rewards that have been paid during finalization.
struct AggregatedStats {
uint256 rewardsAvailable;
uint256 numPoolsToFinalize;
uint256 totalFeesCollected;
uint256 totalWeightedStake;
uint256 totalRewardsFinalized;
}
/// @dev Encapsulates a balance for the current and next epochs.
/// Note that these balances may be stale if the current epoch
/// is greater than `currentEpoch`.
/// @param currentEpoch the current epoch
/// @param currentEpochBalance balance in the current epoch.
/// @param nextEpochBalance balance in `currentEpoch+1`.
struct StoredBalance {
uint64 currentEpoch;
uint96 currentEpochBalance;
uint96 nextEpochBalance;
}
/// @dev Statuses that stake can exist in.
/// Any stake can be (re)delegated effective at the next epoch
/// Undelegated stake can be withdrawn if it is available in both the current and next epoch
enum StakeStatus {
UNDELEGATED,
DELEGATED
}
/// @dev Info used to describe a status.
/// @param status of the stake.
/// @param poolId Unique Id of pool. This is set when status=DELEGATED.
struct StakeInfo {
StakeStatus status;
bytes32 poolId;
}
/// @dev Struct to represent a fraction.
/// @param numerator of fraction.
/// @param denominator of fraction.
struct Fraction {
uint256 numerator;
uint256 denominator;
}
/// @dev Holds the metadata for a staking pool.
/// @param operator of the pool.
/// @param operatorShare Fraction of the total balance owned by the operator, in ppm.
struct Pool {
address operator;
uint32 operatorShare;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
interface IZrxVault {
/// @dev Emmitted whenever a StakingProxy is set in a vault.
event StakingProxySet(address stakingProxyAddress);
/// @dev Emitted when the Staking contract is put into Catastrophic Failure Mode
/// @param sender Address of sender (`msg.sender`)
event InCatastrophicFailureMode(address sender);
/// @dev Emitted when Zrx Tokens are deposited into the vault.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens deposited.
event Deposit(
address indexed staker,
uint256 amount
);
/// @dev Emitted when Zrx Tokens are withdrawn from the vault.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens withdrawn.
event Withdraw(
address indexed staker,
uint256 amount
);
/// @dev Emitted whenever the ZRX AssetProxy is set.
event ZrxProxySet(address zrxProxyAddress);
/// @dev Sets the address of the StakingProxy contract.
/// Note that only the contract staker can call this function.
/// @param _stakingProxyAddress Address of Staking proxy contract.
function setStakingProxy(address _stakingProxyAddress)
external;
/// @dev Vault enters into Catastrophic Failure Mode.
/// *** WARNING - ONCE IN CATOSTROPHIC FAILURE MODE, YOU CAN NEVER GO BACK! ***
/// Note that only the contract staker can call this function.
function enterCatastrophicFailure()
external;
/// @dev Sets the Zrx proxy.
/// Note that only the contract staker can call this.
/// Note that this can only be called when *not* in Catastrophic Failure mode.
/// @param zrxProxyAddress Address of the 0x Zrx Proxy.
function setZrxProxy(address zrxProxyAddress)
external;
/// @dev Deposit an `amount` of Zrx Tokens from `staker` into the vault.
/// Note that only the Staking contract can call this.
/// Note that this can only be called when *not* in Catastrophic Failure mode.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens to deposit.
function depositFrom(address staker, uint256 amount)
external;
/// @dev Withdraw an `amount` of Zrx Tokens to `staker` from the vault.
/// Note that only the Staking contract can call this.
/// Note that this can only be called when *not* in Catastrophic Failure mode.
/// @param staker of Zrx Tokens.
/// @param amount of Zrx Tokens to withdraw.
function withdrawFrom(address staker, uint256 amount)
external;
/// @dev Withdraw ALL Zrx Tokens to `staker` from the vault.
/// Note that this can only be called when *in* Catastrophic Failure mode.
/// @param staker of Zrx Tokens.
function withdrawAllFrom(address staker)
external
returns (uint256);
/// @dev Returns the balance in Zrx Tokens of the `staker`
/// @return Balance in Zrx.
function balanceOf(address staker)
external
view
returns (uint256);
/// @dev Returns the entire balance of Zrx tokens in the vault.
function balanceOfZrxVault()
external
view
returns (uint256);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IProtocolFees {
// Logs updates to the protocol fee multiplier.
event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier);
// Logs updates to the protocolFeeCollector address.
event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector);
/// @dev Allows the owner to update the protocol fee multiplier.
/// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier.
function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier)
external;
/// @dev Allows the owner to update the protocolFeeCollector address.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
external;
/// @dev Returns the protocolFeeMultiplier
function protocolFeeMultiplier()
external
view
returns (uint256);
/// @dev Returns the protocolFeeCollector address
function protocolFeeCollector()
external
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibEIP1271.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IWallet.sol";
import "./interfaces/IEIP1271Wallet.sol";
import "./interfaces/ISignatureValidator.sol";
import "./interfaces/IEIP1271Data.sol";
import "./MixinTransactions.sol";
contract MixinSignatureValidator is
LibEIP712ExchangeDomain,
LibEIP1271,
ISignatureValidator,
MixinTransactions
{
using LibBytes for bytes;
using LibOrder for LibOrder.Order;
using LibZeroExTransaction for LibZeroExTransaction.ZeroExTransaction;
// Magic bytes to be returned by `Wallet` signature type validators.
// bytes4(keccak256("isValidWalletSignature(bytes32,address,bytes)"))
bytes4 private constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381;
// Mapping of hash => signer => signed
mapping (bytes32 => mapping (address => bool)) public preSigned;
// Mapping of signer => validator => approved
mapping (address => mapping (address => bool)) public allowedValidators;
/// @dev Approves a hash on-chain.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param hash Any 32-byte hash.
function preSign(bytes32 hash)
external
payable
refundFinalBalanceNoReentry
{
address signerAddress = _getCurrentContextAddress();
preSigned[hash][signerAddress] = true;
}
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf
/// using the `Validator` signature type.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable
refundFinalBalanceNoReentry
{
address signerAddress = _getCurrentContextAddress();
allowedValidators[signerAddress][validatorAddress] = approval;
emit SignatureValidatorApproval(
signerAddress,
validatorAddress,
approval
);
}
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32-byte hash.
/// @param signerAddress Address that should have signed the given hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid `true` if the signature is valid for the given hash and signer.
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid)
{
SignatureType signatureType = _readValidSignatureType(
hash,
signerAddress,
signature
);
// Only hash-compatible signature types can be handled by this
// function.
if (
signatureType == SignatureType.Validator ||
signatureType == SignatureType.EIP1271Wallet
) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INAPPROPRIATE_SIGNATURE_TYPE,
hash,
signerAddress,
signature
));
}
isValid = _validateHashSignatureTypes(
signatureType,
hash,
signerAddress,
signature
);
return isValid;
}
/// @dev Verifies that a signature for an order is valid.
/// @param order The order.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid `true` if the signature is valid for the given order and signer.
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid)
{
bytes32 orderHash = order.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
isValid = _isValidOrderWithHashSignature(
order,
orderHash,
signature
);
return isValid;
}
/// @dev Verifies that a signature for a transaction is valid.
/// @param transaction The transaction.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid `true` if the signature is valid for the given transaction and signer.
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid)
{
bytes32 transactionHash = transaction.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
isValid = _isValidTransactionWithHashSignature(
transaction,
transactionHash,
signature
);
return isValid;
}
/// @dev Verifies that an order, with provided order hash, has been signed
/// by the given signer.
/// @param order The order.
/// @param orderHash The hash of the order.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given order and signer.
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid)
{
address signerAddress = order.makerAddress;
SignatureType signatureType = _readValidSignatureType(
orderHash,
signerAddress,
signature
);
if (signatureType == SignatureType.Validator) {
// The entire order is verified by a validator contract.
isValid = _validateBytesWithValidator(
_encodeEIP1271OrderWithHash(order, orderHash),
orderHash,
signerAddress,
signature
);
} else if (signatureType == SignatureType.EIP1271Wallet) {
// The entire order is verified by a wallet contract.
isValid = _validateBytesWithWallet(
_encodeEIP1271OrderWithHash(order, orderHash),
signerAddress,
signature
);
} else {
// Otherwise, it's one of the hash-only signature types.
isValid = _validateHashSignatureTypes(
signatureType,
orderHash,
signerAddress,
signature
);
}
return isValid;
}
/// @dev Verifies that a transaction, with provided order hash, has been signed
/// by the given signer.
/// @param transaction The transaction.
/// @param transactionHash The hash of the transaction.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given transaction and signer.
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid)
{
address signerAddress = transaction.signerAddress;
SignatureType signatureType = _readValidSignatureType(
transactionHash,
signerAddress,
signature
);
if (signatureType == SignatureType.Validator) {
// The entire transaction is verified by a validator contract.
isValid = _validateBytesWithValidator(
_encodeEIP1271TransactionWithHash(transaction, transactionHash),
transactionHash,
signerAddress,
signature
);
} else if (signatureType == SignatureType.EIP1271Wallet) {
// The entire transaction is verified by a wallet contract.
isValid = _validateBytesWithWallet(
_encodeEIP1271TransactionWithHash(transaction, transactionHash),
signerAddress,
signature
);
} else {
// Otherwise, it's one of the hash-only signature types.
isValid = _validateHashSignatureTypes(
signatureType,
transactionHash,
signerAddress,
signature
);
}
return isValid;
}
/// Validates a hash-only signature type
/// (anything but `Validator` and `EIP1271Wallet`).
function _validateHashSignatureTypes(
SignatureType signatureType,
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
view
returns (bool isValid)
{
// Always invalid signature.
// Like Illegal, this is always implicitly available and therefore
// offered explicitly. It can be implicitly created by providing
// a correctly formatted but incorrect signature.
if (signatureType == SignatureType.Invalid) {
if (signature.length != 1) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
isValid = false;
// Signature using EIP712
} else if (signatureType == SignatureType.EIP712) {
if (signature.length != 66) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
address recovered = ecrecover(
hash,
v,
r,
s
);
isValid = signerAddress == recovered;
// Signed using web3.eth_sign
} else if (signatureType == SignatureType.EthSign) {
if (signature.length != 66) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
uint8 v = uint8(signature[0]);
bytes32 r = signature.readBytes32(1);
bytes32 s = signature.readBytes32(33);
address recovered = ecrecover(
keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
hash
)),
v,
r,
s
);
isValid = signerAddress == recovered;
// Signature verified by wallet contract.
} else if (signatureType == SignatureType.Wallet) {
isValid = _validateHashWithWallet(
hash,
signerAddress,
signature
);
// Otherwise, signatureType == SignatureType.PreSigned
} else {
assert(signatureType == SignatureType.PreSigned);
// Signer signed hash previously using the preSign function.
isValid = preSigned[hash][signerAddress];
}
return isValid;
}
/// @dev Reads the `SignatureType` from a signature with minimal validation.
function _readSignatureType(
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
pure
returns (SignatureType)
{
if (signature.length == 0) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
return SignatureType(uint8(signature[signature.length - 1]));
}
/// @dev Reads the `SignatureType` from the end of a signature and validates it.
function _readValidSignatureType(
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
pure
returns (SignatureType signatureType)
{
// Read the signatureType from the signature
signatureType = _readSignatureType(
hash,
signerAddress,
signature
);
// Disallow address zero because ecrecover() returns zero on failure.
if (signerAddress == address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_SIGNER,
hash,
signerAddress,
signature
));
}
// Ensure signature is supported
if (uint8(signatureType) >= uint8(SignatureType.NSignatureTypes)) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.UNSUPPORTED,
hash,
signerAddress,
signature
));
}
// Always illegal signature.
// This is always an implicit option since a signer can create a
// signature array with invalid type or length. We may as well make
// it an explicit option. This aids testing and analysis. It is
// also the initialization value for the enum type.
if (signatureType == SignatureType.Illegal) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.ILLEGAL,
hash,
signerAddress,
signature
));
}
return signatureType;
}
/// @dev ABI encodes an order and hash with a selector to be passed into
/// an EIP1271 compliant `isValidSignature` function.
function _encodeEIP1271OrderWithHash(
LibOrder.Order memory order,
bytes32 orderHash
)
private
pure
returns (bytes memory encoded)
{
return abi.encodeWithSelector(
IEIP1271Data(address(0)).OrderWithHash.selector,
order,
orderHash
);
}
/// @dev ABI encodes a transaction and hash with a selector to be passed into
/// an EIP1271 compliant `isValidSignature` function.
function _encodeEIP1271TransactionWithHash(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash
)
private
pure
returns (bytes memory encoded)
{
return abi.encodeWithSelector(
IEIP1271Data(address(0)).ZeroExTransactionWithHash.selector,
transaction,
transactionHash
);
}
/// @dev Verifies a hash and signature using logic defined by Wallet contract.
/// @param hash Any 32 byte hash.
/// @param walletAddress Address that should have signed the given hash
/// and defines its own signature verification method.
/// @param signature Proof that the hash has been signed by signer.
/// @return True if the signature is validated by the Wallet.
function _validateHashWithWallet(
bytes32 hash,
address walletAddress,
bytes memory signature
)
private
view
returns (bool)
{
// Backup length of signature
uint256 signatureLength = signature.length;
// Temporarily remove signatureType byte from end of signature
signature.writeLength(signatureLength - 1);
// Encode the call data.
bytes memory callData = abi.encodeWithSelector(
IWallet(address(0)).isValidSignature.selector,
hash,
signature
);
// Restore the original signature length
signature.writeLength(signatureLength);
// Static call the verification function.
(bool didSucceed, bytes memory returnData) = walletAddress.staticcall(callData);
// Return the validity of the signature if the call was successful
if (didSucceed && returnData.length == 32) {
return returnData.readBytes4(0) == LEGACY_WALLET_MAGIC_VALUE;
}
// Revert if the call was unsuccessful
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureWalletError(
hash,
walletAddress,
signature,
returnData
));
}
/// @dev Verifies arbitrary data and a signature via an EIP1271 Wallet
/// contract, where the wallet address is also the signer address.
/// @param data Arbitrary signed data.
/// @param walletAddress Contract that will verify the data and signature.
/// @param signature Proof that the data has been signed by signer.
/// @return isValid True if the signature is validated by the Wallet.
function _validateBytesWithWallet(
bytes memory data,
address walletAddress,
bytes memory signature
)
private
view
returns (bool isValid)
{
isValid = _staticCallEIP1271WalletWithReducedSignatureLength(
walletAddress,
data,
signature,
1 // The last byte of the signature (signatureType) is removed before making the staticcall
);
return isValid;
}
/// @dev Verifies arbitrary data and a signature via an EIP1271 contract
/// whose address is encoded in the signature.
/// @param data Arbitrary signed data.
/// @param hash The hash associated with the data.
/// @param signerAddress Address that should have signed the given hash.
/// @param signature Proof that the data has been signed by signer.
/// @return isValid True if the signature is validated by the validator contract.
function _validateBytesWithValidator(
bytes memory data,
bytes32 hash,
address signerAddress,
bytes memory signature
)
private
view
returns (bool isValid)
{
uint256 signatureLength = signature.length;
if (signatureLength < 21) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.INVALID_LENGTH,
hash,
signerAddress,
signature
));
}
// The validator address is appended to the signature before the signatureType.
// Read the validator address from the signature.
address validatorAddress = signature.readAddress(signatureLength - 21);
// Ensure signer has approved validator.
if (!allowedValidators[signerAddress][validatorAddress]) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureValidatorNotApprovedError(
signerAddress,
validatorAddress
));
}
isValid = _staticCallEIP1271WalletWithReducedSignatureLength(
validatorAddress,
data,
signature,
21 // The last 21 bytes of the signature (validatorAddress + signatureType) are removed before making the staticcall
);
return isValid;
}
/// @dev Performs a staticcall to an EIP1271 compiant `isValidSignature` function and validates the output.
/// @param verifyingContractAddress Address of EIP1271Wallet or Validator contract.
/// @param data Arbitrary signed data.
/// @param signature Proof that the hash has been signed by signer. Bytes will be temporarily be popped
/// off of the signature before calling `isValidSignature`.
/// @param ignoredSignatureBytesLen The amount of bytes that will be temporarily popped off the the signature.
/// @return The validity of the signature.
function _staticCallEIP1271WalletWithReducedSignatureLength(
address verifyingContractAddress,
bytes memory data,
bytes memory signature,
uint256 ignoredSignatureBytesLen
)
private
view
returns (bool)
{
// Backup length of the signature
uint256 signatureLength = signature.length;
// Temporarily remove bytes from signature end
signature.writeLength(signatureLength - ignoredSignatureBytesLen);
bytes memory callData = abi.encodeWithSelector(
IEIP1271Wallet(address(0)).isValidSignature.selector,
data,
signature
);
// Restore original signature length
signature.writeLength(signatureLength);
// Static call the verification function
(bool didSucceed, bytes memory returnData) = verifyingContractAddress.staticcall(callData);
// Return the validity of the signature if the call was successful
if (didSucceed && returnData.length == 32) {
return returnData.readBytes4(0) == EIP1271_MAGIC_VALUE;
}
// Revert if the call was unsuccessful
LibRichErrors.rrevert(LibExchangeRichErrors.EIP1271SignatureError(
verifyingContractAddress,
data,
signature,
returnData
));
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract LibEIP1271 {
// Magic bytes returned by EIP1271 wallets on success.
bytes4 constant public EIP1271_MAGIC_VALUE = 0x20c13b0b;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibEIP712.sol";
library LibZeroExTransaction {
using LibZeroExTransaction for ZeroExTransaction;
// Hash for the EIP712 0x transaction schema
// keccak256(abi.encodePacked(
// "ZeroExTransaction(",
// "uint256 salt,",
// "uint256 expirationTimeSeconds,",
// "uint256 gasPrice,",
// "address signerAddress,",
// "bytes data",
// ")"
// ));
bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508;
struct ZeroExTransaction {
uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash.
uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires.
uint256 gasPrice; // gasPrice that transaction is required to be executed with.
address signerAddress; // Address of transaction signer.
bytes data; // AbiV2 encoded calldata.
}
/// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator.
/// @param transaction 0x transaction structure.
/// @return EIP712 typed data hash of the transaction.
function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 transactionHash)
{
// Hash the transaction with the domain separator of the Exchange contract.
transactionHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
transaction.getStructHash()
);
return transactionHash;
}
/// @dev Calculates EIP712 hash of the 0x transaction struct.
/// @param transaction 0x transaction structure.
/// @return EIP712 hash of the transaction struct.
function getStructHash(ZeroExTransaction memory transaction)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;
bytes memory data = transaction.data;
uint256 salt = transaction.salt;
uint256 expirationTimeSeconds = transaction.expirationTimeSeconds;
uint256 gasPrice = transaction.gasPrice;
address signerAddress = transaction.signerAddress;
// Assembly for more efficiently computing:
// result = keccak256(abi.encodePacked(
// schemaHash,
// salt,
// expirationTimeSeconds,
// gasPrice,
// uint256(signerAddress),
// keccak256(data)
// ));
assembly {
// Compute hash of data
let dataHash := keccak256(add(data, 32), mload(data))
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), salt) // salt
mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds
mstore(add(memPtr, 96), gasPrice) // gasPrice
mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress
mstore(add(memPtr, 160), dataHash) // hash of data
// Compute hash
result := keccak256(memPtr, 192)
}
return result;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
contract IWallet {
/// @dev Validates a hash with the `Wallet` signature type.
/// @param hash Message hash that is signed.
/// @param signature Proof of signing.
/// @return magicValue `bytes4(0xb0671381)` if the signature check succeeds.
function isValidSignature(
bytes32 hash,
bytes calldata signature
)
external
view
returns (bytes4 magicValue);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-utils/contracts/src/LibEIP1271.sol";
contract IEIP1271Wallet is
LibEIP1271
{
/// @dev Verifies that a signature is valid.
/// @param data Arbitrary signed data.
/// @param signature Proof that data has been signed.
/// @return magicValue bytes4(0x20c13b0b) if the signature check succeeds.
function isValidSignature(
bytes calldata data,
bytes calldata signature
)
external
view
returns (bytes4 magicValue);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
contract ISignatureValidator {
// Allowed signature types.
enum SignatureType {
Illegal, // 0x00, default value
Invalid, // 0x01
EIP712, // 0x02
EthSign, // 0x03
Wallet, // 0x04
Validator, // 0x05
PreSigned, // 0x06
EIP1271Wallet, // 0x07
NSignatureTypes // 0x08, number of signature types. Always leave at end.
}
event SignatureValidatorApproval(
address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures.
address indexed validatorAddress, // Address of signature validator contract.
bool isApproved // Approval or disapproval of validator contract.
);
/// @dev Approves a hash on-chain.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param hash Any 32-byte hash.
function preSign(bytes32 hash)
external
payable;
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable;
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32-byte hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid `true` if the signature is valid for the given hash and signer.
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for an order is valid.
/// @param order The order.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given order and signer.
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for a transaction is valid.
/// @param transaction The transaction.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given transaction and signer.
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that an order, with provided order hash, has been signed
/// by the given signer.
/// @param order The order.
/// @param orderHash The hash of the order.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given order and signer.
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid);
/// @dev Verifies that a transaction, with provided order hash, has been signed
/// by the given signer.
/// @param transaction The transaction.
/// @param transactionHash The hash of the transaction.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given transaction and signer.
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
// solhint-disable
contract IEIP1271Data {
/// @dev This function's selector is used when ABI encoding the order
/// and hash into a byte array before calling `isValidSignature`.
/// This function serves no other purpose.
function OrderWithHash(
LibOrder.Order calldata order,
bytes32 orderHash
)
external
pure;
/// @dev This function's selector is used when ABI encoding the transaction
/// and hash into a byte array before calling `isValidSignature`.
/// This function serves no other purpose.
function ZeroExTransactionWithHash(
LibZeroExTransaction.ZeroExTransaction calldata transaction,
bytes32 transactionHash
)
external
pure;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-utils/contracts/src/Refundable.sol";
import "./interfaces/ITransactions.sol";
import "./interfaces/ISignatureValidator.sol";
contract MixinTransactions is
Refundable,
LibEIP712ExchangeDomain,
ISignatureValidator,
ITransactions
{
using LibZeroExTransaction for LibZeroExTransaction.ZeroExTransaction;
// Mapping of transaction hash => executed
// This prevents transactions from being executed more than once.
mapping (bytes32 => bool) public transactionsExecuted;
// Address of current transaction signer
address public currentContextAddress;
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction structure.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
payable
disableRefundUntilEnd
returns (bytes memory)
{
return _executeTransaction(transaction, signature);
}
/// @dev Executes a batch of Exchange method calls in the context of signer(s).
/// @param transactions Array of 0x transaction structures.
/// @param signatures Array of proofs that transactions have been signed by signer(s).
/// @return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions(
LibZeroExTransaction.ZeroExTransaction[] memory transactions,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (bytes[] memory)
{
uint256 length = transactions.length;
bytes[] memory returnData = new bytes[](length);
for (uint256 i = 0; i != length; i++) {
returnData[i] = _executeTransaction(transactions[i], signatures[i]);
}
return returnData;
}
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction structure.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function _executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
internal
returns (bytes memory)
{
bytes32 transactionHash = transaction.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
_assertExecutableTransaction(
transaction,
signature,
transactionHash
);
// Set the current transaction signer
address signerAddress = transaction.signerAddress;
_setCurrentContextAddressIfRequired(signerAddress, signerAddress);
// Execute transaction
transactionsExecuted[transactionHash] = true;
(bool didSucceed, bytes memory returnData) = address(this).delegatecall(transaction.data);
if (!didSucceed) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionExecutionError(
transactionHash,
returnData
));
}
// Reset current transaction signer if it was previously updated
_setCurrentContextAddressIfRequired(signerAddress, address(0));
emit TransactionExecution(transactionHash);
return returnData;
}
/// @dev Validates context for executeTransaction. Succeeds or throws.
/// @param transaction 0x transaction structure.
/// @param signature Proof that transaction has been signed by signer.
/// @param transactionHash EIP712 typed data hash of 0x transaction.
function _assertExecutableTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature,
bytes32 transactionHash
)
internal
view
{
// Check transaction is not expired
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= transaction.expirationTimeSeconds) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionError(
LibExchangeRichErrors.TransactionErrorCodes.EXPIRED,
transactionHash
));
}
// Validate that transaction is executed with the correct gasPrice
uint256 requiredGasPrice = transaction.gasPrice;
if (tx.gasprice != requiredGasPrice) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionGasPriceError(
transactionHash,
tx.gasprice,
requiredGasPrice
));
}
// Prevent `executeTransaction` from being called when context is already set
address currentContextAddress_ = currentContextAddress;
if (currentContextAddress_ != address(0)) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionInvalidContextError(
transactionHash,
currentContextAddress_
));
}
// Validate transaction has not been executed
if (transactionsExecuted[transactionHash]) {
LibRichErrors.rrevert(LibExchangeRichErrors.TransactionError(
LibExchangeRichErrors.TransactionErrorCodes.ALREADY_EXECUTED,
transactionHash
));
}
// Validate signature
// Transaction always valid if signer is sender of transaction
address signerAddress = transaction.signerAddress;
if (signerAddress != msg.sender && !_isValidTransactionWithHashSignature(
transaction,
transactionHash,
signature
)
) {
LibRichErrors.rrevert(LibExchangeRichErrors.SignatureError(
LibExchangeRichErrors.SignatureErrorCodes.BAD_TRANSACTION_SIGNATURE,
transactionHash,
signerAddress,
signature
));
}
}
/// @dev Sets the currentContextAddress if the current context is not msg.sender.
/// @param signerAddress Address of the transaction signer.
/// @param contextAddress The current context address.
function _setCurrentContextAddressIfRequired(
address signerAddress,
address contextAddress
)
internal
{
if (signerAddress != msg.sender) {
currentContextAddress = contextAddress;
}
}
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function _getCurrentContextAddress()
internal
view
returns (address)
{
address currentContextAddress_ = currentContextAddress;
address contextAddress = currentContextAddress_ == address(0) ? msg.sender : currentContextAddress_;
return contextAddress;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
contract ITransactions {
// TransactionExecution event is emitted when a ZeroExTransaction is executed.
event TransactionExecution(bytes32 indexed transactionHash);
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
payable
returns (bytes memory);
/// @dev Executes a batch of Exchange method calls in the context of signer(s).
/// @param transactions Array of 0x transactions containing salt, signerAddress, and data.
/// @param signatures Array of proofs that transactions have been signed by signer(s).
/// @return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions(
LibZeroExTransaction.ZeroExTransaction[] memory transactions,
bytes[] memory signatures
)
public
payable
returns (bytes[] memory);
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function _getCurrentContextAddress()
internal
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-utils/contracts/src/LibRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "./interfaces/IExchangeCore.sol";
import "./interfaces/IWrapperFunctions.sol";
import "./MixinExchangeCore.sol";
contract MixinWrapperFunctions is
IWrapperFunctions,
MixinExchangeCore
{
using LibSafeMath for uint256;
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = _fillOrKillOrder(
order,
takerAssetFillAmount,
signature
);
return fillResults;
}
/// @dev Executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults[] memory fillResults)
{
uint256 ordersLength = orders.length;
fillResults = new LibFillResults.FillResults[](ordersLength);
for (uint256 i = 0; i != ordersLength; i++) {
fillResults[i] = _fillOrder(
orders[i],
takerAssetFillAmounts[i],
signatures[i]
);
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrKillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
refundFinalBalanceNoReentry
returns (LibFillResults.FillResults[] memory fillResults)
{
uint256 ordersLength = orders.length;
fillResults = new LibFillResults.FillResults[](ordersLength);
for (uint256 i = 0; i != ordersLength; i++) {
fillResults[i] = _fillOrKillOrder(
orders[i],
takerAssetFillAmounts[i],
signatures[i]
);
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (LibFillResults.FillResults[] memory fillResults)
{
uint256 ordersLength = orders.length;
fillResults = new LibFillResults.FillResults[](ordersLength);
for (uint256 i = 0; i != ordersLength; i++) {
fillResults[i] = _fillOrderNoThrow(
orders[i],
takerAssetFillAmounts[i],
signatures[i]
);
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (LibFillResults.FillResults memory fillResults)
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// Calculate the remaining amount of takerAsset to sell
uint256 remainingTakerAssetFillAmount = takerAssetFillAmount.safeSub(fillResults.takerAssetFilledAmount);
// Attempt to sell the remaining amount of takerAsset
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
orders[i],
remainingTakerAssetFillAmount,
signatures[i]
);
// Update amounts filled and fees paid by maker and taker
fillResults = LibFillResults.addFillResults(fillResults, singleFillResults);
// Stop execution if the entire amount of takerAsset has been sold
if (fillResults.takerAssetFilledAmount >= takerAssetFillAmount) {
break;
}
}
return fillResults;
}
/// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
disableRefundUntilEnd
returns (LibFillResults.FillResults memory fillResults)
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// Calculate the remaining amount of makerAsset to buy
uint256 remainingMakerAssetFillAmount = makerAssetFillAmount.safeSub(fillResults.makerAssetFilledAmount);
// Convert the remaining amount of makerAsset to buy into remaining amount
// of takerAsset to sell, assuming entire amount can be sold in the current order
uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil(
orders[i].takerAssetAmount,
orders[i].makerAssetAmount,
remainingMakerAssetFillAmount
);
// Attempt to sell the remaining amount of takerAsset
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
orders[i],
remainingTakerAssetFillAmount,
signatures[i]
);
// Update amounts filled and fees paid by maker and taker
fillResults = LibFillResults.addFillResults(fillResults, singleFillResults);
// Stop execution if the entire amount of makerAsset has been bought
if (fillResults.makerAssetFilledAmount >= makerAssetFillAmount) {
break;
}
}
return fillResults;
}
/// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Minimum amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = marketSellOrdersNoThrow(orders, takerAssetFillAmount, signatures);
if (fillResults.takerAssetFilledAmount < takerAssetFillAmount) {
LibRichErrors.rrevert(LibExchangeRichErrors.IncompleteFillError(
LibExchangeRichErrors.IncompleteFillErrorCode.INCOMPLETE_MARKET_SELL_ORDERS,
takerAssetFillAmount,
fillResults.takerAssetFilledAmount
));
}
}
/// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Minimum amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = marketBuyOrdersNoThrow(orders, makerAssetFillAmount, signatures);
if (fillResults.makerAssetFilledAmount < makerAssetFillAmount) {
LibRichErrors.rrevert(LibExchangeRichErrors.IncompleteFillError(
LibExchangeRichErrors.IncompleteFillErrorCode.INCOMPLETE_MARKET_BUY_ORDERS,
makerAssetFillAmount,
fillResults.makerAssetFilledAmount
));
}
}
/// @dev Executes multiple calls of cancelOrder.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public
payable
refundFinalBalanceNoReentry
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
_cancelOrder(orders[i]);
}
}
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function _fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
fillResults = _fillOrder(
order,
takerAssetFillAmount,
signature
);
if (fillResults.takerAssetFilledAmount != takerAssetFillAmount) {
LibRichErrors.rrevert(LibExchangeRichErrors.IncompleteFillError(
LibExchangeRichErrors.IncompleteFillErrorCode.INCOMPLETE_FILL_ORDER,
takerAssetFillAmount,
fillResults.takerAssetFilledAmount
));
}
return fillResults;
}
/// @dev Fills the input order.
/// Returns a null FillResults instance if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function _fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchangeCore(address(0)).fillOrder.selector,
order,
takerAssetFillAmount,
signature
);
(bool didSucceed, bytes memory returnData) = address(this).delegatecall(fillOrderCalldata);
if (didSucceed) {
assert(returnData.length == 160);
fillResults = abi.decode(returnData, (LibFillResults.FillResults));
}
// fillResults values will be 0 by default if call was unsuccessful
return fillResults;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
contract IWrapperFunctions {
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrKillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Minimum amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Minimum amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of cancelOrder.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public
payable;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "./MixinAssetProxyDispatcher.sol";
contract MixinTransferSimulator is
MixinAssetProxyDispatcher
{
/// @dev This function may be used to simulate any amount of transfers
/// As they would occur through the Exchange contract. Note that this function
/// will always revert, even if all transfers are successful. However, it may
/// be used with eth_call or with a try/catch pattern in order to simulate
/// the results of the transfers.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @param fromAddresses Array containing the `from` addresses that correspond with each transfer.
/// @param toAddresses Array containing the `to` addresses that correspond with each transfer.
/// @param amounts Array containing the amounts that correspond to each transfer.
/// @return This function does not return a value. However, it will always revert with
/// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful.
function simulateDispatchTransferFromCalls(
bytes[] memory assetData,
address[] memory fromAddresses,
address[] memory toAddresses,
uint256[] memory amounts
)
public
{
uint256 length = assetData.length;
for (uint256 i = 0; i != length; i++) {
_dispatchTransferFrom(
// The index is passed in as `orderHash` so that a failed transfer can be quickly identified when catching the error
bytes32(i),
assetData[i],
fromAddresses[i],
toAddresses[i],
amounts[i]
);
}
revert("TRANSFERS_SUCCESSFUL");
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "./IExchangeCore.sol";
import "./IProtocolFees.sol";
import "./IMatchOrders.sol";
import "./ISignatureValidator.sol";
import "./ITransactions.sol";
import "./IAssetProxyDispatcher.sol";
import "./IWrapperFunctions.sol";
import "./ITransferSimulator.sol";
// solhint-disable no-empty-blocks
contract IExchange is
IProtocolFees,
IExchangeCore,
IMatchOrders,
ISignatureValidator,
ITransactions,
IAssetProxyDispatcher,
ITransferSimulator,
IWrapperFunctions
{}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
contract ITransferSimulator {
/// @dev This function may be used to simulate any amount of transfers
/// As they would occur through the Exchange contract. Note that this function
/// will always revert, even if all transfers are successful. However, it may
/// be used with eth_call or with a try/catch pattern in order to simulate
/// the results of the transfers.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @param fromAddresses Array containing the `from` addresses that correspond with each transfer.
/// @param toAddresses Array containing the `to` addresses that correspond with each transfer.
/// @param amounts Array containing the amounts that correspond to each transfer.
/// @return This function does not return a value. However, it will always revert with
/// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful.
function simulateDispatchTransferFromCalls(
bytes[] memory assetData,
address[] memory fromAddresses,
address[] memory toAddresses,
uint256[] memory amounts
)
public;
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibExchangeRichErrors.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
contract LibExchangeRichErrorDecoder {
using LibBytes for bytes;
/// @dev Decompose an ABI-encoded SignatureError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return signerAddress The expected signer of the hash.
/// @return signature The full signature.
function decodeSignatureError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.SignatureErrorCodes errorCode,
bytes32 hash,
address signerAddress,
bytes memory signature
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureErrorSelector());
uint8 _errorCode;
(_errorCode, hash, signerAddress, signature) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32, address, bytes)
);
errorCode = LibExchangeRichErrors.SignatureErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded SignatureValidatorError.
/// @param encoded ABI-encoded revert error.
/// @return signerAddress The expected signer of the hash.
/// @return signature The full signature bytes.
/// @return errorData The revert data thrown by the validator contract.
function decodeEIP1271SignatureError(bytes memory encoded)
public
pure
returns (
address verifyingContractAddress,
bytes memory data,
bytes memory signature,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.EIP1271SignatureErrorSelector());
(verifyingContractAddress, data, signature, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(address, bytes, bytes, bytes)
);
}
/// @dev Decompose an ABI-encoded SignatureValidatorNotApprovedError.
/// @param encoded ABI-encoded revert error.
/// @return signerAddress The expected signer of the hash.
/// @return validatorAddress The expected validator.
function decodeSignatureValidatorNotApprovedError(bytes memory encoded)
public
pure
returns (
address signerAddress,
address validatorAddress
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureValidatorNotApprovedErrorSelector());
(signerAddress, validatorAddress) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(address, address)
);
}
/// @dev Decompose an ABI-encoded SignatureWalletError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return signerAddress The expected signer of the hash.
/// @return signature The full signature bytes.
/// @return errorData The revert data thrown by the validator contract.
function decodeSignatureWalletError(bytes memory encoded)
public
pure
returns (
bytes32 hash,
address signerAddress,
bytes memory signature,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.SignatureWalletErrorSelector());
(hash, signerAddress, signature, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, address, bytes, bytes)
);
}
/// @dev Decompose an ABI-encoded OrderStatusError.
/// @param encoded ABI-encoded revert error.
/// @return orderHash The order hash.
/// @return orderStatus The order status.
function decodeOrderStatusError(bytes memory encoded)
public
pure
returns (
bytes32 orderHash,
LibOrder.OrderStatus orderStatus
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.OrderStatusErrorSelector());
uint8 _orderStatus;
(orderHash, _orderStatus) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, uint8)
);
orderStatus = LibOrder.OrderStatus(_orderStatus);
}
/// @dev Decompose an ABI-encoded OrderStatusError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode Error code that corresponds to invalid maker, taker, or sender.
/// @return orderHash The order hash.
/// @return contextAddress The maker, taker, or sender address
function decodeExchangeInvalidContextError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.ExchangeContextErrorCodes errorCode,
bytes32 orderHash,
address contextAddress
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.ExchangeInvalidContextErrorSelector());
uint8 _errorCode;
(_errorCode, orderHash, contextAddress) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32, address)
);
errorCode = LibExchangeRichErrors.ExchangeContextErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded FillError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return orderHash The order hash.
function decodeFillError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.FillErrorCodes errorCode,
bytes32 orderHash
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.FillErrorSelector());
uint8 _errorCode;
(_errorCode, orderHash) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32)
);
errorCode = LibExchangeRichErrors.FillErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded OrderEpochError.
/// @param encoded ABI-encoded revert error.
/// @return makerAddress The order maker.
/// @return orderSenderAddress The order sender.
/// @return currentEpoch The current epoch for the maker.
function decodeOrderEpochError(bytes memory encoded)
public
pure
returns (
address makerAddress,
address orderSenderAddress,
uint256 currentEpoch
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.OrderEpochErrorSelector());
(makerAddress, orderSenderAddress, currentEpoch) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(address, address, uint256)
);
}
/// @dev Decompose an ABI-encoded AssetProxyExistsError.
/// @param encoded ABI-encoded revert error.
/// @return assetProxyId Id of asset proxy.
/// @return assetProxyAddress The address of the asset proxy.
function decodeAssetProxyExistsError(bytes memory encoded)
public
pure
returns (
bytes4 assetProxyId, address assetProxyAddress)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyExistsErrorSelector());
(assetProxyId, assetProxyAddress) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes4, address)
);
}
/// @dev Decompose an ABI-encoded AssetProxyDispatchError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return orderHash Hash of the order being dispatched.
/// @return assetData Asset data of the order being dispatched.
function decodeAssetProxyDispatchError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.AssetProxyDispatchErrorCodes errorCode,
bytes32 orderHash,
bytes memory assetData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyDispatchErrorSelector());
uint8 _errorCode;
(_errorCode, orderHash, assetData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32, bytes)
);
errorCode = LibExchangeRichErrors.AssetProxyDispatchErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded AssetProxyTransferError.
/// @param encoded ABI-encoded revert error.
/// @return orderHash Hash of the order being dispatched.
/// @return assetData Asset data of the order being dispatched.
/// @return errorData ABI-encoded revert data from the asset proxy.
function decodeAssetProxyTransferError(bytes memory encoded)
public
pure
returns (
bytes32 orderHash,
bytes memory assetData,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.AssetProxyTransferErrorSelector());
(orderHash, assetData, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, bytes, bytes)
);
}
/// @dev Decompose an ABI-encoded NegativeSpreadError.
/// @param encoded ABI-encoded revert error.
/// @return leftOrderHash Hash of the left order being matched.
/// @return rightOrderHash Hash of the right order being matched.
function decodeNegativeSpreadError(bytes memory encoded)
public
pure
returns (
bytes32 leftOrderHash,
bytes32 rightOrderHash
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.NegativeSpreadErrorSelector());
(leftOrderHash, rightOrderHash) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, bytes32)
);
}
/// @dev Decompose an ABI-encoded TransactionError.
/// @param encoded ABI-encoded revert error.
/// @return errorCode The error code.
/// @return transactionHash Hash of the transaction.
function decodeTransactionError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.TransactionErrorCodes errorCode,
bytes32 transactionHash
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.TransactionErrorSelector());
uint8 _errorCode;
(_errorCode, transactionHash) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, bytes32)
);
errorCode = LibExchangeRichErrors.TransactionErrorCodes(_errorCode);
}
/// @dev Decompose an ABI-encoded TransactionExecutionError.
/// @param encoded ABI-encoded revert error.
/// @return transactionHash Hash of the transaction.
/// @return errorData Error thrown by exeucteTransaction().
function decodeTransactionExecutionError(bytes memory encoded)
public
pure
returns (
bytes32 transactionHash,
bytes memory errorData
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.TransactionExecutionErrorSelector());
(transactionHash, errorData) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(bytes32, bytes)
);
}
/// @dev Decompose an ABI-encoded IncompleteFillError.
/// @param encoded ABI-encoded revert error.
/// @return orderHash Hash of the order being filled.
function decodeIncompleteFillError(bytes memory encoded)
public
pure
returns (
LibExchangeRichErrors.IncompleteFillErrorCode errorCode,
uint256 expectedAssetFillAmount,
uint256 actualAssetFillAmount
)
{
_assertSelectorBytes(encoded, LibExchangeRichErrors.IncompleteFillErrorSelector());
uint8 _errorCode;
(_errorCode, expectedAssetFillAmount, actualAssetFillAmount) = abi.decode(
encoded.sliceDestructive(4, encoded.length),
(uint8, uint256, uint256)
);
errorCode = LibExchangeRichErrors.IncompleteFillErrorCode(_errorCode);
}
/// @dev Revert if the leading 4 bytes of `encoded` is not `selector`.
function _assertSelectorBytes(bytes memory encoded, bytes4 selector)
private
pure
{
bytes4 actualSelector = LibBytes.readBytes4(encoded, 0);
require(
actualSelector == selector,
"BAD_SELECTOR"
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "../src/Exchange.sol";
/// @dev A version of the Exchange contract with simplified signature validation
/// and a `_dispatchTransferFrom()` that only logs arguments.
/// See the `IsolatedExchangeWrapper` and `isolated_fill_order` tests
/// for example usage.
contract IsolatedExchange is
Exchange
{
// solhint-disable no-unused-vars
event DispatchTransferFromCalled(
bytes32 orderHash,
bytes assetData,
address from,
address to,
uint256 amount
);
// solhint-disable no-empty-blocks
constructor ()
public
Exchange(1337)
{}
/// @dev Overridden to only log arguments and revert on certain assetDatas.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
emit DispatchTransferFromCalled(
orderHash,
assetData,
from,
to,
amount
);
// Fail if the first byte is 0.
if (assetData.length > 0 && assetData[0] == 0x00) {
revert("TRANSFER_FAILED");
}
}
/// @dev Overridden to simplify signature validation.
/// Unfortunately, this is `view`, so it can't log arguments.
function _isValidOrderWithHashSignature(
LibOrder.Order memory,
bytes32,
bytes memory signature
)
internal
view
returns (bool isValid)
{
// '0x01' in the first byte is valid.
return signature.length == 2 && signature[0] == 0x01;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibReentrancyGuardRichErrors.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
/// @dev A version of the Exchange that exposes a `testReentrancyGuard()`
/// function which is used to test whether a function is protected by the
/// `nonReentrant` modifier. Several internal functions have also been
/// overridden to simplify constructing valid calls to external functions.
contract ReentrancyTester is
Exchange
{
using LibBytes for bytes;
// solhint-disable no-empty-blocks
// solhint-disable no-unused-vars
constructor ()
public
// Initialize the exchange with a fixed chainId ("test" in hex).
Exchange(0x74657374)
{}
/// @dev Calls a public function to check if it is reentrant.
/// Because this function uses the `nonReentrant` modifier, if
/// the function being called is also guarded by the `nonReentrant` modifier,
/// it will revert when it returns.
function isReentrant(bytes calldata fnCallData)
external
nonReentrant
returns (bool allowsReentrancy)
{
(bool didSucceed, bytes memory resultData) = address(this).delegatecall(fnCallData);
if (didSucceed) {
allowsReentrancy = true;
} else {
if (resultData.equals(LibReentrancyGuardRichErrors.IllegalReentrancyError())) {
allowsReentrancy = false;
} else {
allowsReentrancy = true;
}
}
}
/// @dev Overridden to revert on unsuccessful fillOrder call.
function _fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchangeCore(address(0)).fillOrder.selector,
order,
takerAssetFillAmount,
signature
);
(bool didSucceed, bytes memory returnData) = address(this).delegatecall(fillOrderCalldata);
if (didSucceed) {
assert(returnData.length == 128);
fillResults = abi.decode(returnData, (LibFillResults.FillResults));
return fillResults;
}
// Revert and rethrow error if unsuccessful
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
/// @dev Overridden to always succeed.
function _fillOrder(
LibOrder.Order memory order,
uint256,
bytes memory
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
fillResults.makerAssetFilledAmount = order.makerAssetAmount;
fillResults.takerAssetFilledAmount = order.takerAssetAmount;
fillResults.makerFeePaid = order.makerFee;
fillResults.takerFeePaid = order.takerFee;
}
/// @dev Overridden to always succeed.
function _fillOrKillOrder(
LibOrder.Order memory order,
uint256,
bytes memory
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
fillResults.makerAssetFilledAmount = order.makerAssetAmount;
fillResults.takerAssetFilledAmount = order.takerAssetAmount;
fillResults.makerFeePaid = order.makerFee;
fillResults.takerFeePaid = order.takerFee;
}
/// @dev Overridden to always succeed.
function _executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory,
bytes memory
)
internal
returns (bytes memory resultData)
{
// Should already point to an empty array.
return resultData;
}
/// @dev Overridden to always succeed.
function _batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory,
bytes[] memory,
bool
)
internal
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults)
{
uint256 numOrders = leftOrders.length;
batchMatchedFillResults.left = new LibFillResults.FillResults[](numOrders);
batchMatchedFillResults.right = new LibFillResults.FillResults[](numOrders);
for (uint256 i = 0; i < numOrders; ++i) {
batchMatchedFillResults.left[i] = LibFillResults.FillResults({
makerAssetFilledAmount: leftOrders[i].makerAssetAmount,
takerAssetFilledAmount: leftOrders[i].takerAssetAmount,
makerFeePaid: leftOrders[i].makerFee,
takerFeePaid: leftOrders[i].takerFee,
protocolFeePaid: 0
});
batchMatchedFillResults.right[i] = LibFillResults.FillResults({
makerAssetFilledAmount: rightOrders[i].makerAssetAmount,
takerAssetFilledAmount: rightOrders[i].takerAssetAmount,
makerFeePaid: rightOrders[i].makerFee,
takerFeePaid: rightOrders[i].takerFee,
protocolFeePaid: 0
});
}
}
/// @dev Overridden to always succeed.
function _matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory,
bytes memory,
bool
)
internal
returns (LibFillResults.MatchedFillResults memory matchedFillResults)
{
matchedFillResults.left = LibFillResults.FillResults({
makerAssetFilledAmount: leftOrder.makerAssetAmount,
takerAssetFilledAmount: leftOrder.takerAssetAmount,
makerFeePaid: leftOrder.makerFee,
takerFeePaid: leftOrder.takerFee,
protocolFeePaid: 0
});
matchedFillResults.right = LibFillResults.FillResults({
makerAssetFilledAmount: rightOrder.makerAssetAmount,
takerAssetFilledAmount: rightOrder.takerAssetAmount,
makerFeePaid: rightOrder.makerFee,
takerFeePaid: rightOrder.takerFee,
protocolFeePaid: 0
});
}
/// @dev Overridden to do nothing.
function _cancelOrder(LibOrder.Order memory order)
internal
{}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "../src/MixinAssetProxyDispatcher.sol";
import "../src/MixinTransferSimulator.sol";
contract TestAssetProxyDispatcher is
MixinAssetProxyDispatcher,
MixinTransferSimulator
{
function dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
public
{
_dispatchTransferFrom(orderHash, assetData, from, to, amount);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
// solhint-disable no-empty-blocks
contract TestExchangeInternals is
Exchange
{
event DispatchTransferFromCalled(
bytes32 orderHash,
bytes assetData,
address from,
address to,
uint256 amount
);
constructor (uint256 chainId)
public
Exchange(chainId)
{}
function assertValidMatch(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder
)
public
view
{
_assertValidMatch(
leftOrder,
rightOrder,
leftOrder.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH),
rightOrder.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH)
);
}
/// @dev Call `_updateFilledState()` but first set `filled[order]` to
/// `orderTakerAssetFilledAmount`.
function testUpdateFilledState(
LibOrder.Order memory order,
address takerAddress,
bytes32 orderHash,
uint256 orderTakerAssetFilledAmount,
LibFillResults.FillResults memory fillResults
)
public
payable
{
filled[LibOrder.getTypedDataHash(order, EIP712_EXCHANGE_DOMAIN_HASH)] = orderTakerAssetFilledAmount;
_updateFilledState(
order,
takerAddress,
orderHash,
orderTakerAssetFilledAmount,
fillResults
);
}
function settleOrder(
bytes32 orderHash,
LibOrder.Order memory order,
address takerAddress,
LibFillResults.FillResults memory fillResults
)
public
{
_settleOrder(orderHash, order, takerAddress, fillResults);
}
function settleMatchOrders(
bytes32 leftOrderHash,
bytes32 rightOrderHash,
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
address takerAddress,
LibFillResults.MatchedFillResults memory matchedFillResults
)
public
{
_settleMatchedOrders(
leftOrderHash,
rightOrderHash,
leftOrder,
rightOrder,
takerAddress,
matchedFillResults
);
}
/// @dev Overidden to only log arguments so we can test `_settleOrder()`.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
emit DispatchTransferFromCalled(
orderHash,
assetData,
from,
to,
amount
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
// Exchange contract with settlement disabled so we can just check `_fillOrder()``
// calculations.
contract TestFillRounding is
Exchange
{
// solhint-disable no-empty-blocks
constructor ()
public
// Initialize the exchange with a fixed chainId ("test" in hex).
Exchange(0x74657374)
{}
function _settleOrder(
bytes32 orderHash,
LibOrder.Order memory order,
address takerAddress,
LibFillResults.FillResults memory fillResults
)
internal
{
// No-op.
}
function _assertFillableOrder(
LibOrder.Order memory order,
LibOrder.OrderInfo memory orderInfo,
address takerAddress,
bytes memory signature
)
internal
view
{
// No-op.
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
import "../src/libs/LibExchangeRichErrorDecoder.sol";
// solhint-disable no-empty-blocks
contract TestLibExchangeRichErrorDecoder is
LibExchangeRichErrorDecoder
{}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol";
// solhint-disable no-unused-vars, no-empty-blocks
contract TestProtocolFeeCollector {
address private _wethAddress;
constructor (
address wethAddress
)
public
{
_wethAddress = wethAddress;
}
function ()
external
payable
{}
/// @dev Pays a protocol fee in WETH (Forwarder orders will always pay protocol fees in WETH).
/// @param makerAddress The address of the order's maker.
/// @param payerAddress The address of the protocol fee payer.
/// @param protocolFeePaid The protocol fee that should be paid.
function payProtocolFee(
address makerAddress,
address payerAddress,
uint256 protocolFeePaid
)
external
payable
{
if (msg.value != protocolFeePaid) {
require(
msg.value == 0,
"No value should be forwarded to collector when paying fee in WETH"
);
// Transfer the protocol fee to this address in WETH.
IEtherToken(_wethAddress).transferFrom(
payerAddress,
address(this),
protocolFeePaid
);
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "../src/Exchange.sol";
contract TestProtocolFees is
Exchange
{
// solhint-disable no-empty-blocks
constructor ()
public
Exchange(1337)
{}
// @dev Expose a setter to the `protocolFeeCollector` state variable.
// @param newProtocolFeeCollector The address that should be made the `protocolFeeCollector`.
function setProtocolFeeCollector(address newProtocolFeeCollector)
external
{
protocolFeeCollector = newProtocolFeeCollector;
}
// @dev Expose a setter to the `protocolFeeMultiplier` state variable.
// @param newProtocolFeeMultiplier The number that should be made the `protocolFeeMultiplier`.
function setProtocolFeeMultiplier(uint256 newProtocolFeeMultiplier)
external
{
protocolFeeMultiplier = newProtocolFeeMultiplier;
}
// @dev Stub out the `_assertFillableOrder` function because we don't actually
// care about order validation in these tests.
function _assertFillableOrder(
LibOrder.Order memory,
LibOrder.OrderInfo memory,
address,
bytes memory
)
internal
view
{} // solhint-disable-line no-empty-blocks
// @dev Stub out the `_assertFillableOrder` function because we don't actually
// care about transfering through proxies in these tests.
function _dispatchTransferFrom(
bytes32 orderHash,
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{} // solhint-disable-line no-empty-blocks
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/LibSafeMath.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "./TestProtocolFees.sol";
// Disable solhint to allow for more informative comments.
// solhint-disable
contract TestProtocolFeesReceiver {
// Attach LibSafeMath to uint256
using LibSafeMath for uint256;
/* Testing Constants */
// A constant to represent a maker address.
address internal constant makerAddress1 = address(1);
// A constant to represent a maker address that is distinct from the
// other maker address.
address internal constant makerAddress2 = address(2);
/* Testing State */
// A struct that provides a schema for test data that should be logged.
struct TestLog {
address loggedMaker;
address loggedPayer;
uint256 loggedProtocolFeePaid;
uint256 loggedValue;
}
// The array of testLogs that will be added to by `payProtocolFee` and processed by the tests.
TestLog[] testLogs;
/* Testing Functions */
/// @dev Tests the `batchFillOrders` function's payment of protocol fees.
/// @param testProtocolFees The TestProtocolFees that should be tested against.
/// @param protocolFeeMultiplier The protocol fee multiplier that should be registered
/// in the test suite before executing `batchFillOrders`.
/// @param numberOfOrders The number of orders that should be created and executed for this test.
/// @param shouldSetProtocolFeeCollector A boolean value indicating whether or not this contract
/// should be registered as the `protocolFeeCollector`.
function testBatchFillOrdersProtocolFees(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
uint256 numberOfOrders,
bool shouldSetProtocolFeeCollector
)
external
payable
handleState(testProtocolFees, protocolFeeMultiplier, shouldSetProtocolFeeCollector)
{
// Create empty arrays for taker asset filled amounts and signatures, which will suffice for this test.
uint256[] memory takerAssetFilledAmounts = new uint256[](numberOfOrders);
bytes[] memory signatures = new bytes[](numberOfOrders);
// Construct an array of orders in which every even-indexed order has a makerAddress of makerAddress1 and
// every odd-indexed order has a makerAddress of makerAddress2. This is done to make sure that the correct
// makers are being logged.
LibOrder.Order[] memory orders = new LibOrder.Order[](numberOfOrders);
for (uint256 i = 0; i < numberOfOrders; i++) {
orders[i] = createOrder(i % 2 == 0 ? makerAddress1 : makerAddress2);
}
// Forward all of the value sent to the contract to `batchFillOrders()`.
testProtocolFees.batchFillOrders.value(msg.value)(orders, takerAssetFilledAmounts, signatures);
// If the `protocolFeeCollector` was set, ensure that the protocol fees were paid correctly.
// Otherwise, the protocol fees should not have been paid.
if (shouldSetProtocolFeeCollector) {
// Ensure that the correct number of test logs were recorded.
require(testLogs.length == numberOfOrders, "Incorrect number of test logs in batchFillOrders test");
// Calculate the expected protocol fee.
uint256 expectedProtocolFeePaid = tx.gasprice.safeMul(protocolFeeMultiplier);
// Set the expected available balance for the first log.
uint256 expectedAvailableBalance = msg.value;
// Verify all of the test logs.
for (uint256 i = 0; i < testLogs.length; i++) {
// Verify the logged data.
verifyTestLog(
testLogs[i],
expectedAvailableBalance, // expectedAvailableBalance
i % 2 == 0 ? makerAddress1 : makerAddress2, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
// Set the expected available balance for the next log.
expectedAvailableBalance = expectedAvailableBalance >= expectedProtocolFeePaid ?
expectedAvailableBalance - expectedProtocolFeePaid :
expectedAvailableBalance;
}
} else {
// Ensure that zero test logs were created.
require(testLogs.length == 0, "Incorrect number of test logs in batchFillOrders test");
}
}
/// @dev Tests the `fillOrder` function's payment of protocol fees.
/// @param testProtocolFees The TestProtocolFees that should be tested against.
/// @param protocolFeeMultiplier The protocol fee multiplier that should be registered
/// in the test suite before executing `fillOrder`.
/// @param shouldSetProtocolFeeCollector A boolean value indicating whether or not this contract
/// should be registered as the `protocolFeeCollector`.
function testFillOrderProtocolFees(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
bool shouldSetProtocolFeeCollector
)
external
payable
handleState(testProtocolFees, protocolFeeMultiplier, shouldSetProtocolFeeCollector)
{
// Create empty values for the takerAssetFilledAmount and the signature since these values don't
// matter for this test.
uint256 takerAssetFilledAmount = 0;
bytes memory signature = new bytes(0);
// Construct an of order with distinguishing information.
LibOrder.Order memory order = createOrder(makerAddress1);
// Forward all of the value sent to the contract to `fillOrder()`.
testProtocolFees.fillOrder.value(msg.value)(order, takerAssetFilledAmount, signature);
// If the `protocolFeeCollector` was set, ensure that the protocol fee was paid correctly.
// Otherwise, the protocol fee should not have been paid.
if (shouldSetProtocolFeeCollector) {
// Ensure that only one test log was created by the call to `fillOrder()`.
require(testLogs.length == 1, "Incorrect number of test logs in fillOrder test");
// Calculate the expected protocol fee.
uint256 expectedProtocolFeePaid = tx.gasprice.safeMul(protocolFeeMultiplier);
// Verify that the test log that was created is correct.
verifyTestLog(
testLogs[0],
msg.value, // expectedAvailableBalance
makerAddress1, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
} else {
// Ensure that zero test logs were created.
require(testLogs.length == 0, "Incorrect number of test logs in fillOrder test");
}
}
/// @dev Tests the `matchOrders` function's payment of protocol fees.
/// @param testProtocolFees The TestProtocolFees that should be tested against.
/// @param protocolFeeMultiplier The protocol fee multiplier that should be registered
/// in the test suite before executing `matchOrders`.
/// @param shouldSetProtocolFeeCollector A boolean value indicating whether or not this contract
/// should be registered as the `protocolFeeCollector`.
function testMatchOrdersProtocolFees(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
bool shouldSetProtocolFeeCollector
)
external
payable
handleState(testProtocolFees, protocolFeeMultiplier, shouldSetProtocolFeeCollector)
{
// Create two empty signatures since signatures are not used in this test.
bytes memory leftSignature = new bytes(0);
bytes memory rightSignature = new bytes(0);
// Construct a distinguished left order.
LibOrder.Order memory leftOrder = createOrder(makerAddress1);
// Construct a distinguished right order.
LibOrder.Order memory rightOrder = createOrder(makerAddress2);
// Forward all of the value sent to the contract to `matchOrders()`.
testProtocolFees.matchOrders.value(msg.value)(leftOrder, rightOrder, leftSignature, rightSignature);
// If the `protocolFeeCollector` was set, ensure that the protocol fee was paid correctly.
// Otherwise, the protocol fee should not have been paid.
if (shouldSetProtocolFeeCollector) {
// Ensure that only one test log was created by the call to `fillOrder()`.
require(testLogs.length == 2, "Incorrect number of test logs in matchOrders test");
// Calculate the expected protocol fee.
uint256 expectedProtocolFeePaid = tx.gasprice.safeMul(protocolFeeMultiplier);
// Set the expected available balance for the first log.
uint256 expectedAvailableBalance = msg.value;
// Verify that the first test log that was created is correct.
verifyTestLog(
testLogs[0],
expectedAvailableBalance, // expectedAvailableBalance
makerAddress1, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
// Set the expected available balance for the second log.
expectedAvailableBalance = expectedAvailableBalance >= expectedProtocolFeePaid ?
expectedAvailableBalance - expectedProtocolFeePaid :
expectedAvailableBalance;
// Verify that the second test log that was created is correct.
verifyTestLog(
testLogs[1],
expectedAvailableBalance, // expectedAvailableBalance
makerAddress2, // expectedMakerAddress
address(this), // expectedPayerAddress
expectedProtocolFeePaid // expectedProtocolFeePaid
);
} else {
// Ensure that zero test logs were created.
require(testLogs.length == 0, "Incorrect number of test logs in matchOrders test");
}
}
/* Verification Functions */
/// @dev Verifies a test log against expected values.
/// @param expectedAvailableBalance The balance that should be available when this call is made.
/// This is important especially for tests on wrapper functions.
/// @param expectedMakerAddress The expected maker address to be recorded in `payProtocolFee`.
/// @param expectedPayerAddress The expected payer address to be recorded in `payProtocolFee`.
/// @param expectedProtocolFeePaid The expected protocol fee paidto be recorded in `payProtocolFee`.
function verifyTestLog(
TestLog memory log,
uint256 expectedAvailableBalance,
address expectedMakerAddress,
address expectedPayerAddress,
uint256 expectedProtocolFeePaid
)
internal
pure
{
// If the expected available balance was sufficient to pay the protocol fee, the protocol fee
// should have been paid in ether. Otherwise, no ether should be sent to pay the protocol fee.
if (expectedAvailableBalance >= expectedProtocolFeePaid) {
// Ensure that the protocol fee was paid in ether.
require(
log.loggedValue == expectedProtocolFeePaid,
"Incorrect eth was received during fillOrder test when adequate ETH was sent"
);
} else {
// Ensure that the protocol fee was not paid in ether.
require(
log.loggedValue == 0,
"Incorrect eth was received during fillOrder test when inadequate ETH was sent"
);
}
// Ensure that the correct data was logged.
require(log.loggedMaker == expectedMakerAddress, "Incorrect maker address was logged");
require(log.loggedPayer == expectedPayerAddress, "Incorrect taker address was logged");
require(log.loggedProtocolFeePaid == expectedProtocolFeePaid, "Incorrect protocol fee was logged");
}
/* Testing Convenience Functions */
/// @dev Sets up state that is necessary for tests and then cleans up the state that was written
/// to so that test cases can be thought of as atomic.
/// @param testProtocolFees The TestProtocolFees contract that is being used during testing.
/// @param protocolFeeMultiplier The protocolFeeMultiplier of this test case.
/// @param shouldSetProtocolFeeCollector A boolean value that indicates whether or not this address
/// should be made the protocol fee collector.
modifier handleState(
TestProtocolFees testProtocolFees,
uint256 protocolFeeMultiplier,
bool shouldSetProtocolFeeCollector
)
{
// If necessary, set the protocol fee collector field in the exchange.
if (shouldSetProtocolFeeCollector) {
testProtocolFees.setProtocolFeeCollector(address(this));
}
// Set the protocol fee multiplier in the exchange.
testProtocolFees.setProtocolFeeMultiplier(protocolFeeMultiplier);
// Execute the test.
_;
}
/// @dev Constructs an order with a specified maker address.
/// @param makerAddress The maker address of the order.
function createOrder(address makerAddress)
internal
pure
returns (LibOrder.Order memory order)
{
order.makerAddress = makerAddress;
order.makerAssetAmount = 1; // This is 1 so that it doesn't trigger a `DivionByZero()` error.
order.takerAssetAmount = 1; // This is 1 so that it doesn't trigger a `DivionByZero()` error.
}
/* Protocol Fee Receiver and Fallback */
/// @dev Receives payments of protocol fees from a TestProtocolFees contract
/// and records the data provided and the message value sent.
/// @param makerAddress The maker address that should be recorded.
/// @param payerAddress The payer address that should be recorded.
/// @param protocolFeePaid The protocol fee that should be recorded.
function payProtocolFee(
address makerAddress,
address payerAddress,
uint256 protocolFeePaid
)
external
payable
{
// Push the collected data into `testLogs`.
testLogs.push(TestLog({
loggedMaker: makerAddress,
loggedPayer: payerAddress,
loggedProtocolFeePaid: protocolFeePaid,
loggedValue: msg.value
}));
}
/// @dev A payable fallback function that makes this contract "payable". This is necessary to allow
/// this contract to gracefully handle refunds from TestProtocolFees contracts.
function ()
external
payable
{}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "../src/Exchange.sol";
contract TestTransactions is
Exchange
{
event ExecutableCalled(
bytes data,
bytes returnData,
address contextAddress
);
constructor ()
public
Exchange(1337)
{} // solhint-disable-line no-empty-blocks
function setCurrentContextAddress(address context)
external
{
currentContextAddress = context;
}
function setTransactionExecuted(bytes32 hash)
external
{
transactionsExecuted[hash] = true;
}
function setCurrentContextAddressIfRequired(address signerAddress, address context)
external
{
_setCurrentContextAddressIfRequired(signerAddress, context);
}
function getCurrentContextAddress()
external
view
returns (address)
{
return _getCurrentContextAddress();
}
function assertExecutableTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
{
return _assertExecutableTransaction(
transaction,
signature,
transaction.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH)
);
}
// This function will execute arbitrary calldata via a delegatecall. This is highly unsafe to use in production, and this
// is only meant to be used during testing.
function executable(
bool shouldSucceed,
bytes memory data,
bytes memory returnData
)
public
returns (bytes memory)
{
emit ExecutableCalled(
data,
returnData,
currentContextAddress
);
require(shouldSucceed, "EXECUTABLE_FAILED");
if (data.length != 0) {
(bool didSucceed, bytes memory callResultData) = address(this).delegatecall(data); // This is a delegatecall to preserve the `msg.sender` field
if (!didSucceed) {
assembly { revert(add(callResultData, 0x20), mload(callResultData)) }
}
}
return returnData;
}
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory,
bytes32,
bytes memory signature
)
internal
view
returns (bool)
{
if (
signature.length == 2 &&
signature[0] == 0x0 &&
signature[1] == 0x0
) {
return false;
}
return true;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibEIP712ExchangeDomain.sol";
import "@0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol";
import "@0x/contracts-utils/contracts/src/LibBytes.sol";
import "@0x/contracts-utils/contracts/src/LibEIP1271.sol";
import "../src/interfaces/IEIP1271Data.sol";
// solhint-disable no-unused-vars
contract TestValidatorWallet is
LibEIP1271
{
using LibBytes for bytes;
// Magic bytes to be returned by `Wallet` signature type validators.
// bytes4(keccak256("isValidWalletSignature(bytes32,address,bytes)"))
bytes4 private constant LEGACY_WALLET_MAGIC_VALUE = 0xb0671381;
/// @dev Revert reason for `Revert` `ValidatorAction`.
string constant public REVERT_REASON = "you shall not pass";
enum ValidatorAction {
// Return failure (default)
Reject,
// Return success
Accept,
// Revert
Revert,
// Update state
UpdateState,
// Ensure the signature hash matches what was prepared
MatchSignatureHash,
// Return boolean `true`,
ReturnTrue,
// Return no data.
ReturnNothing,
NTypes
}
/// @dev The Exchange domain hash..
LibEIP712ExchangeDomain internal _exchange;
/// @dev Internal state to modify.
uint256 internal _state = 1;
/// @dev What action to execute when a hash is validated .
mapping (bytes32 => ValidatorAction) internal _hashActions;
/// @dev keccak256 of the expected signature data for a hash.
mapping (bytes32 => bytes32) internal _hashSignatureHashes;
constructor(address exchange) public {
_exchange = LibEIP712ExchangeDomain(exchange);
}
/// @dev Approves an ERC20 token to spend tokens from this address.
/// @param token Address of ERC20 token.
/// @param spender Address that will spend tokens.
/// @param value Amount of tokens spender is approved to spend.
function approveERC20(
address token,
address spender,
uint256 value
)
external
{
IERC20Token(token).approve(spender, value);
}
/// @dev Prepares this contract to validate a signature.
/// @param hash The hash.
/// @param action Action to take.
/// @param signatureHash keccak256 of the expected signature data.
function prepare(
bytes32 hash,
ValidatorAction action,
bytes32 signatureHash
)
external
{
if (uint8(action) >= uint8(ValidatorAction.NTypes)) {
revert("UNSUPPORTED_VALIDATOR_ACTION");
}
_hashActions[hash] = action;
_hashSignatureHashes[hash] = signatureHash;
}
/// @dev Validates data signed by either `EIP1271Wallet` or `Validator` signature types.
/// @param data Abi-encoded data (Order or ZeroExTransaction) and a hash.
/// @param signature Signature for `data`.
/// @return magicValue `EIP1271_MAGIC_VALUE` if the signature check succeeds.
function isValidSignature(
bytes memory data,
bytes memory signature
)
public
returns (bytes4 magicValue)
{
bytes32 hash = _decodeAndValidateHashFromEncodedData(data);
ValidatorAction action = _hashActions[hash];
if (action == ValidatorAction.Reject) {
magicValue = 0x0;
} else if (action == ValidatorAction.Accept) {
magicValue = EIP1271_MAGIC_VALUE;
} else if (action == ValidatorAction.Revert) {
revert(REVERT_REASON);
} else if (action == ValidatorAction.UpdateState) {
_updateState();
} else if (action == ValidatorAction.ReturnNothing) {
assembly {
return(0x0, 0)
}
} else if (action == ValidatorAction.ReturnTrue) {
assembly {
mstore(0x0, 1)
return(0x0, 32)
}
} else {
assert(action == ValidatorAction.MatchSignatureHash);
bytes32 expectedSignatureHash = _hashSignatureHashes[hash];
if (keccak256(signature) == expectedSignatureHash) {
magicValue = EIP1271_MAGIC_VALUE;
}
}
}
/// @dev Validates a hash with the `Wallet` signature type.
/// @param hash Message hash that is signed.
/// @param signature Proof of signing.
/// @return `LEGACY_WALLET_MAGIC_VALUE` if the signature check succeeds.
function isValidSignature(
bytes32 hash,
bytes memory signature
)
public
returns (bytes4 magicValue)
{
ValidatorAction action = _hashActions[hash];
if (action == ValidatorAction.Reject) {
magicValue = bytes4(0);
} else if (action == ValidatorAction.Accept) {
magicValue = LEGACY_WALLET_MAGIC_VALUE;
} else if (action == ValidatorAction.Revert) {
revert(REVERT_REASON);
} else if (action == ValidatorAction.UpdateState) {
_updateState();
} else if (action == ValidatorAction.ReturnNothing) {
assembly {
return(0x0, 0)
}
} else if (action == ValidatorAction.ReturnTrue) {
assembly {
mstore(0x0, 1)
return(0x0, 32)
}
} else {
assert(action == ValidatorAction.MatchSignatureHash);
bytes32 expectedSignatureHash = _hashSignatureHashes[hash];
if (keccak256(signature) == expectedSignatureHash) {
magicValue = LEGACY_WALLET_MAGIC_VALUE;
}
}
}
/// @dev Increments state variable to trigger a state change.
function _updateState()
private
{
_state++;
}
function _decodeAndValidateHashFromEncodedData(bytes memory data)
private
view
returns (bytes32 hash)
{
bytes4 dataId = data.readBytes4(0);
if (dataId == IEIP1271Data(address(0)).OrderWithHash.selector) {
// Decode the order and hash
LibOrder.Order memory order;
(order, hash) = abi.decode(
data.slice(4, data.length),
(LibOrder.Order, bytes32)
);
// Use the Exchange to calculate the hash of the order and assert
// that it matches the one we extracted previously.
require(
LibOrder.getTypedDataHash(order, _exchange.EIP712_EXCHANGE_DOMAIN_HASH()) == hash,
"UNEXPECTED_ORDER_HASH"
);
} else if (dataId == IEIP1271Data(address(0)).ZeroExTransactionWithHash.selector) {
// Decode the transaction and hash
LibZeroExTransaction.ZeroExTransaction memory transaction;
(transaction, hash) = abi.decode(
data.slice(4, data.length),
(LibZeroExTransaction.ZeroExTransaction, bytes32)
);
// Use the Exchange to calculate the hash of the transaction and assert
// that it matches the one we extracted previously.
require(
LibZeroExTransaction.getTypedDataHash(transaction, _exchange.EIP712_EXCHANGE_DOMAIN_HASH()) == hash,
"UNEXPECTED_TRANSACTION_HASH"
);
} else {
revert("EXPECTED_NO_DATA_TYPE");
}
return hash;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol";
import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol";
import "../src/Exchange.sol";
/// @dev A version of the Exchange contract with`_fillOrder()`,
/// `_cancelOrder()`, and `getOrderInfo()` overridden to test
/// `MixinWrapperFunctions`.
contract TestWrapperFunctions is
Exchange
{
uint8 internal constant MAX_ORDER_STATUS = uint8(LibOrder.OrderStatus.CANCELLED);
uint256 internal constant ALWAYS_FAILING_SALT = uint256(-1);
string internal constant ALWAYS_FAILING_SALT_REVERT_REASON = "ALWAYS_FAILING_SALT";
// solhint-disable no-unused-vars
event FillOrderCalled(
LibOrder.Order order,
uint256 takerAssetFillAmount,
bytes signature
);
event CancelOrderCalled(
LibOrder.Order order
);
// solhint-disable no-empty-blocks
constructor ()
public
// Initialize the exchange with a fixed chainId ("test" in hex).
Exchange(0x74657374)
{}
/// @dev Overridden to be deterministic and simplified.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo)
{
// Lower uint128 of `order.salt` is the `orderTakerAssetFilledAmount`.
orderInfo.orderTakerAssetFilledAmount = uint128(order.salt);
// High byte of `order.salt` is the `orderStatus`.
orderInfo.orderStatus = uint8(order.salt >> 248) % (MAX_ORDER_STATUS + 1);
orderInfo.orderHash = order.getTypedDataHash(EIP712_EXCHANGE_DOMAIN_HASH);
}
function fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults)
{
return _fillOrderNoThrow(
order,
takerAssetFillAmount,
signature
);
}
/// @dev Overridden to log arguments, be deterministic, and revert with certain inputs.
function _fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
emit FillOrderCalled(
order,
takerAssetFillAmount,
signature
);
// Fail if the salt is ALWAYS_FAILING_SALT.
if (order.salt == ALWAYS_FAILING_SALT) {
revert(ALWAYS_FAILING_SALT_REVERT_REASON);
}
// We aren't interested in correctness here because we are testing the
// behavior of the caller, not `_fillOrder()` itself. We just need some
// values that the caller can aggregate together.
fillResults.makerAssetFilledAmount = order.makerAssetAmount;
fillResults.takerAssetFilledAmount = order.takerAssetAmount;
fillResults.makerFeePaid = order.makerFee;
fillResults.takerFeePaid = order.takerFee;
fillResults.protocolFeePaid = protocolFeeMultiplier;
}
/// @dev Overridden to only log arguments and revert with certain inputs.
function _cancelOrder(
LibOrder.Order memory order
)
internal
{
emit CancelOrderCalled(
order
);
// Fail if the salt is ALWAYS_FAILING_SALT.
if (order.salt == ALWAYS_FAILING_SALT) {
revert(ALWAYS_FAILING_SALT_REVERT_REASON);
}
}
}
| Locked state of mutex. | contract ReentrancyGuard {
bool private _locked = false;
modifier nonReentrant() {
_lockMutexOrThrowIfAlreadyLocked();
_;
_unlockMutex();
}
function _lockMutexOrThrowIfAlreadyLocked()
internal
{
if (_locked) {
LibRichErrors.rrevert(
LibReentrancyGuardRichErrors.IllegalReentrancyError()
);
}
}
function _lockMutexOrThrowIfAlreadyLocked()
internal
{
if (_locked) {
LibRichErrors.rrevert(
LibReentrancyGuardRichErrors.IllegalReentrancyError()
);
}
}
_locked = true;
function _unlockMutex()
internal
{
_locked = false;
}
}
| 1,007,250 | [
1,
8966,
919,
434,
9020,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
868,
8230,
12514,
16709,
288,
203,
203,
565,
1426,
3238,
389,
15091,
273,
629,
31,
203,
203,
203,
203,
565,
9606,
1661,
426,
8230,
970,
1435,
288,
203,
3639,
389,
739,
11433,
30180,
2047,
9430,
8966,
5621,
203,
3639,
389,
31,
203,
3639,
389,
26226,
11433,
5621,
203,
565,
289,
203,
203,
565,
445,
389,
739,
11433,
30180,
2047,
9430,
8966,
1435,
203,
3639,
2713,
203,
565,
288,
203,
3639,
309,
261,
67,
15091,
13,
288,
203,
5411,
10560,
22591,
4229,
18,
86,
266,
1097,
12,
203,
7734,
10560,
426,
8230,
12514,
16709,
22591,
4229,
18,
12195,
426,
8230,
12514,
668,
1435,
203,
5411,
11272,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
739,
11433,
30180,
2047,
9430,
8966,
1435,
203,
3639,
2713,
203,
565,
288,
203,
3639,
309,
261,
67,
15091,
13,
288,
203,
5411,
10560,
22591,
4229,
18,
86,
266,
1097,
12,
203,
7734,
10560,
426,
8230,
12514,
16709,
22591,
4229,
18,
12195,
426,
8230,
12514,
668,
1435,
203,
5411,
11272,
203,
3639,
289,
203,
565,
289,
203,
203,
3639,
389,
15091,
273,
638,
31,
203,
565,
445,
389,
26226,
11433,
1435,
203,
3639,
2713,
203,
565,
288,
203,
3639,
389,
15091,
273,
629,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'IOReceipts' token contract
//
// Deployed to : 0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717
// Symbol : IOR
// Name : IOReceipt
// Total supply: 100000000
// Decimals : 8
//
// Enjoy.
//
// (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract IOReceipts is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function IOReceipts() public {
symbol = "IOR";
name = "IOReceipt";
decimals = 8;
_totalSupply = 210000000.00000000;
balances[0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717] = _totalSupply;
Transfer(address(0), 0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract IOReceipts is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function IOReceipts() public {
symbol = "IOR";
name = "IOReceipt";
decimals = 8;
_totalSupply = 210000000.00000000;
balances[0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717] = _totalSupply;
Transfer(address(0), 0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 10,049,614 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1665,
4779,
27827,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
1665,
4779,
27827,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
45,
916,
14432,
203,
3639,
508,
273,
315,
4294,
15636,
14432,
203,
3639,
15105,
273,
1725,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
9035,
17877,
18,
12648,
31,
203,
3639,
324,
26488,
63,
20,
16275,
11290,
38,
70,
42,
4577,
72,
5520,
42,
23,
40,
6030,
37,
29,
9988,
3600,
3672,
10321,
73,
26,
38,
4700,
22,
41,
2163,
19192,
27,
4033,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
12279,
12,
2867,
12,
20,
3631,
374,
16275,
11290,
38,
70,
42,
4577,
72,
5520,
42,
23,
40,
6030,
37,
29,
9988,
3600,
3672,
10321,
73,
26,
38,
4700,
22,
41,
2163,
19192,
27,
4033,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
5381,
1135,
2
]
|
pragma solidity ^0.4.13;
/**
* 10X contract
* Copyright 2017, TheWolf
*
* An infinite crowdfunding lottery token
* Using a permanent delivery of tokens as a reward to the lost bids.
* With a bullet proof random generation algorithm and a lot of inovative features
* With a state machine switching automatically from game mode to crowdfunding mode
*
* Note: the code is free to use for learning purpose or inspiration,
* but identical code used in a commercial product or similar games
* is prohibited: be creative!
*/
/* Math operations with safety checks */
contract safeMath {
function safeMul(uint a, uint b) internal constant returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal constant returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal constant returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal constant returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
/* owned class */
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) revert();
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
/* pass class */
contract pass is owned{
bytes32 internalPass;
function storePassword(string password) internal onlyOwner{
internalPass = sha256(password);
}
modifier protected(string password) {
if ( internalPass!= sha256(password)) revert();
_;
}
function changePassword(string oldPassword, string newPassword) onlyOwner returns(bool) {
if (internalPass== sha256(oldPassword)) {
internalPass = sha256(newPassword);
return true;
}
return false;
}
}
/* blacklist */
contract blacklist is owned, pass{
// change the blacklist status of an address
function setBlacklist(address _adr, bool _value, string _password ) onlyOwner external protected(_password){
require(_adr>0);
require(_adr!=owner);
blacklist[_adr]=_value;
}
// change the blacklist status of an address internal version
function setBlacklistInternal(address _adr, bool _value) onlyOwner internal {
require(_adr>0);
require(_adr!=owner);
blacklist[_adr]=_value;
}
// get the current status of an address, blacklisted or not?
function checkBlacklist(address _adr ) constant external onlyOwner returns(bool){
return blacklist[_adr];
}
mapping (address => bool) blacklist;
}
/* ERC20 Contract definitions */
contract ERC20 {
uint256 public totalETHSupply; // added to the ERC20 for convenience, does not change the protocol
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/* 10X Token Creation and Functionality */
contract TokenBase is ERC20, blacklist, safeMath{
uint public totalAddress;
function TokenBase() { // constructor, first address is owner
addr[0]=msg.sender;
totalAddress=1;
}
// Send to the address _to, value money
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
// Transfer money from one adress _from to another adress _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value ) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
// get the current owner balance
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// transaction approval : check if everything is ok before transfering
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function getAddress(uint _index) constant returns(address adr)
{
require(_index>=0);
require(_index<totalAddress);
return(addr[_index]);
}
function getTotalAddresses() constant returns(uint) {
return(totalAddress);
}
// allowance
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (uint => address) addr;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract THEWOLF10XToken is TokenBase{
string public constant name = "10X Game"; // contract name
string public constant symbol = "10X"; // symbol name
uint256 public constant decimals = 18; // standard size
string public constant version="1.46";
bool public isfundingGoalReached;
bool public isGameOn;
bool public isPaused;
bool public isDebug;
bool public isAutopilot;
bool public isLimited;
bool public isPrintTokenInfinite;
bool public isMaxCap10XReached;
uint public limitMaxCrowdsale;
uint public limitMaxGame;
uint public fundingGoal;
uint public totalTokenSupply;
uint public timeStarted;
uint public deadline;
uint public maxPlayValue;
uint public betNumber;
uint public restartGamePeriod;
uint public playValue;
uint public tokenDeliveryCrowdsalePrice;
uint public tokenDeliveryPlayPrice;
uint private seed;
uint private exresult;
uint256 public tokenCreationCap;
struct transactions { // Struct
address playeraddress;
uint time;
uint betinwai;
uint numberdrawn;
uint playerbet;
bool winornot;
}
event Create10X(address indexed _to, uint256 _value);
event LogMsg(address indexed _from, string Msg);
event FundingReached(address beneficiary, uint fundingRaised);
event GameOnOff(bool state);
event GoalReached(address owner, uint256 goal);
event SwitchingToFundingMode(uint totalETHSupply, uint fundingCurrent);
event InPauseMode(uint date,bool status);
mapping (uint => transactions) public bettable;
// contructor debugging : 5000,2000,10,"10000000","0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db", "0x14723a09acff6d2a60dcdf7aa4aff308fddc160c", "zzzzz",10,4
// Testnet: https://gist.github.com/TheWolf-Patarawan/ae9e8ecf7300fc3abcc8d0863d6f4245
// need this gas to create the contract: 6000000
function THEWOLF10XToken(
uint _fundingGoalInEthers,
uint _tokenPriceForEachEtherCrowdsale,
uint _tokenPriceGame,
uint _tokenInitialSupplyIn10X,
address _addressOwnerTrading1,
address _addressOwnerTrading2,
string _password,
uint _durationInDays
)
{
require(_tokenPriceForEachEtherCrowdsale<=10000 && _tokenPriceForEachEtherCrowdsale>0);
require(_tokenInitialSupplyIn10X * 1 ether>=10000000 * 1 ether); // cannot run with less than 10x4 Million 10X total, safety test in case slippy finger misses a 0
require(msg.sender>0); // using 0 as address is not allowed
isGameOn=false; // open the crowdsale per default
isfundingGoalReached = false;
isPaused=false;
isMaxCap10XReached=false;
fundingGoal = _fundingGoalInEthers * 1 ether; // calculate the funding goal in eth
// WARNING THIS IS FOR DEBUGGING, THIS VALUE MUST BE 0 IN THE LIVE CONTRACT
//------------------------------------------------------------------------
totalETHSupply = 100 ether; // initial ETH funding for testing
//------------------------------------------------------------------------
owner = msg.sender; // save the address of the contract initiator for later use
balances[owner] =_tokenInitialSupplyIn10X * 2 ether; // tokens for the contract (used to deliver tokens to the player) 2x 10 Millions.
balances[_addressOwnerTrading1] = _tokenInitialSupplyIn10X * 1 ether; // 10 M tokens for escrow 1 (buy)
balances[_addressOwnerTrading2] = _tokenInitialSupplyIn10X * 1 ether; // 10 M tokens for escrow 2 (sale)
timeStarted=now; // initialize the timer for the crowdsale, starting now
tokenDeliveryCrowdsalePrice = _tokenPriceForEachEtherCrowdsale; // how many 10X tokens are delivered during the crowdsale
tokenDeliveryPlayPrice=_tokenPriceGame; // price of a token when the game starts
totalTokenSupply=_tokenInitialSupplyIn10X * 1 ether; // initial supply of tokens
tokenCreationCap=_tokenInitialSupplyIn10X * 2 ether; // 20 Millions 10X tokens in the game /10 for ICO / 10 for the game.
storePassword(_password); // hash the password and store the admin password
betNumber=0; // starting, no bets yet
seed=now/4000000000000*3141592653589; // random seed
exresult=1; // random result storage
deadline==now + (_durationInDays * 1 days); // date of the end of the current crowdsale starting now
restartGamePeriod=1; // automatic crowdfunding reset for this time period in days by default
maxPlayValue=safeDiv(totalETHSupply,100); // at starting we can play no more than 2 Eth
isLimited=false; // not limit for buying tokens
isPrintTokenInfinite= false; // we deliver only the tokens we have in stock of true we mint on demand.
limitMaxCrowdsale=0; // the upper limit in case of we want to limit the value per transaction in crowdsale mode
isAutopilot=false; // do not let the contract change its status alone. Set it to true if the owner cannot manage the contract anymore.
limitMaxGame= 2 ether; // cannot play more than 2 ether at the game, if 0 unlimited
}
// determines the token rate
function tokenRate() constant returns(uint) {
if (now>timeStarted && now<deadline && !isGameOn) return tokenDeliveryCrowdsalePrice; // when we are in crowdsale mode
return tokenDeliveryPlayPrice; // when the game is on
}
// Generates and delivers the tokens and the ethers
function makeTokens() payable returns(bool) {
uint256 tokens;
uint256 checkTokenSupply;
maxPlayValue=safeDiv(totalETHSupply,100);
playValue=msg.value;
// check if we exceed the maximum bet possible according to the fund we have.
if (isGameOn==true) {
if (playValue>maxPlayValue) {
LogMsg(msg.sender, "This bet exceed the maximum play value, we cannot accept it, try with a lower amount.");
revert();
}
}
// case of we limit the number of transaction in the Crowdsale mode
if (isLimited==true && isGameOn==false) {
if (balances[msg.sender]>limitMaxCrowdsale) {
LogMsg(msg.sender, "limiting: I am in limited crowdsale mode. You have too many tokens to participate.");
revert();
}
}
if (now<timeStarted) return false; //do not create tokens before it is started
if (playValue == 0) {
//LogMsg(msg.sender, "makeTokens: Cannot receive 0 ETH."); // do not log message, no need to help hackers
return false; // cannot receive 0 ETH
}
if (msg.sender == 0) return false; // sender cannot be null
if (isGameOn) {
// check if we are out of limit
if (limitMaxGame>0) { // 0 is unlimited <>0 then we limit the maximum bet for the game
if (playValue>limitMaxGame) {
LogMsg(msg.sender, "Your bet is > to the limitMaxGame limit. Check the website to see what is the maximum value to bet in the game at this time.");
revert();
}
}
// this is when the game is on (crowdsale finished)
uint bet=lastDecimal(playValue); // this is the number the player bet
uint drawn=rand(0,9);
// store the bets so that the website can list the results
// address playeraddress;
// uint time;
// uint betinwai;
// uint numberdrawn;
// bool winornot;
bettable[betNumber].playeraddress=msg.sender;
bettable[betNumber].time=now;
bettable[betNumber].betinwai=msg.value;
bettable[betNumber].numberdrawn=drawn;
bettable[betNumber].playerbet=bet;
// check if win or not
if (bet==drawn) bettable[betNumber].winornot=true;
else bettable[betNumber].winornot=false;
// case 1 the player wins => we send x*his bet
if (bettable[betNumber].winornot==true) {
uint moneytosend=playValue*tokenRate();
require(totalETHSupply>moneytosend); // not enough money? cancel the transaction
sendEthBack(moneytosend); // x time the ETH bet back to the player and eventually switch to ICO mode
}else{
// case 2 the player looses => we send tokenrate*his bet
if (!isMaxCap10XReached) { // we still have tokens in stock
tokens = safeMul(msg.value,tokenRate()); // send 10X * current rate
checkTokenSupply = safeAdd(totalTokenSupply,tokens); // temporary variable to check the total supply
if (tokens >= totalTokenSupply-(10 ether)) { // we cannot run the game with less than 100 ETH
LogMsg(msg.sender, "Game mode: You are running out of tokens, please add more.");
// need to switch to crowdfunding mode
betNumber++;
resetInternal(restartGamePeriod); // do a new ICO for x day. x is 1 by default but can be changed with externals
return false;
}
// case 3, we have reached the max cap, we cannot deliver any tokens anymore, but the game can continue
}else{
LogMsg(msg.sender, "Cannot deliver tokens. All tokens have been distributed. Hopefully the owner will mint more.");
}
if (checkTokenSupply >= tokenCreationCap) { //
isMaxCap10XReached=true;
LogMsg(msg.sender, "Game mode: We have reached the maximum capitalization.");
betNumber++;
return false;
}
// we are here -> giving tokens to the player.
totalTokenSupply = checkTokenSupply;
balances[msg.sender] += tokens;
}
Create10X(msg.sender, tokens); // event
betNumber++; // increase the bet number index
}else {
// crowdfunding mode
tokens = safeMul(msg.value,tokenRate()); // send 10X * current rate
checkTokenSupply = safeAdd(totalTokenSupply,tokens); // temporary variable to check the total supply
if (!isMaxCap10XReached) {
// case 4, we are in normal crowdfunding mode
if (tokens >= totalTokenSupply-(10 ether) || totalTokenSupply<=10 ether) { //
LogMsg(msg.sender, "Crowdfunding mode: You are running out of tokens, please add more.");
return false; // cannot continue
}
}else{
// case 3, we have reached the max cap, we cannot deliver any tokens anymore.
if (isAutopilot) {
isGameOn=true; // we switch in game mode, since there is no reason to raise any money. End of the crowdsale
GameOnOff(isGameOn);
LogMsg(msg.sender, "Max Cap reached, switching to game mode. End of the Crowdsale");
}else{
LogMsg(msg.sender, "End of the crowdsale. Autopilot is off and I am waiting for the owner to unPause me.");
// we are in manual mode, so we pause the game and wait that owner decide.
isGameOn=true; // we prepare everything to switch to game when owner is ready.
GameOnOff(isGameOn);
isPaused=true;
InPauseMode(now,isPaused);
}
}
// here if we are still in crowdsale mode
updateStatusInternal(); // are we at the end of the crowdsale and other test?
totalETHSupply+=msg.value; // updating the total ETH we received since if we are here that meant that the transaction was successfull
balances[msg.sender] += tokens; // update the balance of the sender with the tokens he purchased
totalTokenSupply = checkTokenSupply; // update the total token supplied
}
return true;
}
function() payable {
require(blacklist[msg.sender]!=true); // blacklist system do not access if in the blacklist
if (isDebug) {
LogMsg(msg.sender, "Debugging something...we will be back soon. Your transaction has been cancelled.");
revert();
}
if (!isPaused) { // if the contract is not paused, otherwise, do nothing
if (!makeTokens()) {
LogMsg(msg.sender, "10X token cannot be delivered. Transaction cancelled.");
revert();
}
}else {
LogMsg(msg.sender, "10X is paused. Please wait until it is running again.");
revert();
}
}
// Reset manually the ICO to do another crowdfunding from external
function reset(uint _value_goal, uint _value_crowdsale, uint _value_game,uint _value_duration, string _password) external onlyOwner protected(_password){
isGameOn=false;
isfundingGoalReached = false;
isPaused=false;
InPauseMode(now,isPaused);
isMaxCap10XReached=false;
tokenDeliveryCrowdsalePrice=_value_crowdsale;
tokenDeliveryPlayPrice=_value_game;
fundingGoal = _value_goal * 1 ether;
owner = msg.sender;
deadline = now + ( _value_duration * 1 days);
timeStarted=now;
updateStatusInternal();
}
// Reset automatically the ICO to do another crowdfunding, duration is in seconds, this is the internal version cheaper in gas
function resetInternal( uint _value_duration) internal {
isGameOn=false; // game mode is off we are doing a crowdfunding
isfundingGoalReached = false;
isPaused=false;
InPauseMode(now,isPaused);
isMaxCap10XReached=false;
deadline = now + (_value_duration* 1 days); // set new duration in days
timeStarted=now;
}
// get the info of a bet in a json table, I want it public for transparency, also the website need this.
function getBet(uint256 _value) public constant returns(uint, uint, uint, uint,bool) {
require(_value<betNumber && _value>=0);
return (bettable[_value].time,bettable[_value].betinwai,bettable[_value].numberdrawn,bettable[_value].playerbet,bettable[_value].winornot);
}
// Sends eth to ethFundAddress (the contract owner) manually
function sendEth(uint256 _value) external onlyOwner {
require(_value >= totalETHSupply);
if(!owner.send(_value) ) { // using send, checking that the operation was successful
LogMsg(msg.sender, "sendEth: 10X cannot send this value of ETH, transaction cancelled.");
revert();
}
// if here send was sucessful
}
// Sends eth back to the player
function sendEthBack(uint256 _value) internal {
require (msg.sender>0);
require (msg.sender != owner); // owner cannot send to himself
uint tmpvalue=_value; // debugging otherwise cannot see this value in the debugger
require (_value>0);
if (_value > totalETHSupply-(10 ether) && totalETHSupply>=10 ether ) { // 100 ETH is the minium for the Bank to run, also check hack attempt with impossible values.
resetInternal(restartGamePeriod); // in days, restartGamePeriod can be set to whatever
LogMsg(msg.sender, "sendEthBack: not enough ETH to perform this operation.");
if (!isAutopilot) { // if we are not in auto pilot, pause the game and let the owner decide.
isPaused=true;
InPauseMode(now,isPaused);
}
}
if(!msg.sender.send(_value) ) {
LogMsg(msg.sender, "sendEthBack: 10X cannot send this value of ETH. Refunding.");
revert();
}
// if here send was sucessful
}
// checks if the goal or time limit has been reached and ends the campaign (switch back in game mode)
function updateStatusInternal() internal returns(bool){
if (now >= deadline) { // did we reached the deadline?
if ( totalETHSupply >= fundingGoal){ // did we raised enough ETH?
isfundingGoalReached = true; // end the crowdfunding
GoalReached(owner, totalETHSupply); // shoot an event to log it
}
isGameOn = true; // crowdsale is closed, let's play the game.
GameOnOff(isGameOn);
if (!isAutopilot) { // we are not in autopilot mode, then pause the game and let the owner decide when to switch to game more.
isPaused=true;
InPauseMode(now,isPaused);
}
}else{ isGameOn=false;} // still in crowdfunding mode, let's continue in this mode
if (totalTokenSupply >= tokenCreationCap) {
isMaxCap10XReached=true;
} else isMaxCap10XReached=false;
return(isGameOn);
}
// checks if the goal or time limit has been reached and ends the campaign (switch back in game mode)
function updateStatus() external onlyOwner returns(bool){ //
if (now >= deadline) { // did we reached the deadline?
if ( totalETHSupply >= fundingGoal){ // did we raised enough ETH?
isfundingGoalReached = true;
GoalReached(owner, totalETHSupply); // shoot an event to log it
}
isGameOn = true; // crowdsale is closed, let's play the game.
GameOnOff(isGameOn);
if (!isAutopilot) { // we are not in autopilot mode, then pause the game and let the owner decide when to switch to game more.
isPaused=true;
InPauseMode(now,isPaused);
}
}else{ isGameOn=false;}
if (totalTokenSupply >= tokenCreationCap) {
isMaxCap10XReached=true;
} else isMaxCap10XReached=false;
return(isGameOn);
}
// Add ETH manually
function addEth() payable external onlyOwner{
if (!isGameOn) {
LogMsg(msg.sender, "addEth: 10X crowdfunding is has not ended. Cannot do that now.");
revert();
}
totalETHSupply += msg.value;
}
// Add tokens manually to the game in ether
function addTokens(uint256 _mintedAmount,string _password) external onlyOwner protected(_password) {
require(_mintedAmount * 1 ether <= 10000000 * 1 ether); // do not add more than 1 Million token, avoid mistake
safeAdd(totalTokenSupply ,_mintedAmount * 1 ether);
}
// Sub tokens manually from the game
function subTokens(uint256 _mintedAmount,string _password) external onlyOwner protected(_password) {
require(_mintedAmount * 1 ether <= 10000000 * 1 ether); // do not sub more than 1 Million Ether, avoid mistake
require(_mintedAmount * 1 ether > totalTokenSupply); // do not go under 0
safeSub(totalTokenSupply ,_mintedAmount * 1 ether);
}
// Give tokens to someone
function giveToken(address _target, uint256 _mintedAmount,string _password) external onlyOwner protected(_password) {
safeAdd(balances[_target],_mintedAmount);
safeAdd(totalTokenSupply,_mintedAmount);
if (isPrintTokenInfinite==true) Transfer(0, owner, _mintedAmount); // if we want to mint ad infinity create token from thin air
Transfer(owner, _target, _mintedAmount); // event
}
// Take tokens from someone
function takeToken(address _target, uint256 _mintedAmount, string _password) external onlyOwner protected(_password) {
safeSub(balances[_target], _mintedAmount);
safeSub(totalTokenSupply,_mintedAmount);
Transfer(0, owner, _mintedAmount); // event
Transfer(owner, _target, _mintedAmount); // event
}
// Is an expeditive way to switch from crowdsale to game mode
function switchToGame(string _password) external onlyOwner protected(_password) {
require(!isGameOn); // re-entrance check
isGameOn = true; // start the game
GameOnOff(isGameOn);
}
// Is an expeditive way to switch from game mode to crowdsale
function switchToCrowdsale(string _password) external onlyOwner protected(_password) {
require(isGameOn); // re-entrance check
isGameOn = false; // start the game
GameOnOff(isGameOn);
}
// random number (miner proof)
function rand(uint _min, uint _max) internal returns (uint){
require(_min>=0);
require(_max>_min);
bytes32 hashVal = bytes32(block.blockhash(block.number - exresult));
if (seed==0) seed=uint(hashVal);
else {
safeAdd(safeDiv(seed,2),safeDiv(uint(hashVal),2));
}
uint result=safeAdd(uint(hashVal)%_max,_min)+1;
exresult=safeAdd(result%200,1);
return uint(result);
}
// Destroy this contract (cry)
function destroyContract(string _password) external onlyOwner protected(_password) {
selfdestruct(owner); // commit suicide!
}
// convert a string to bytes
function stringToBytes( string _s) internal constant returns (bytes){
bytes memory b3 = bytes(_s);
return b3;
}
// take the last byte and extract a number between 1-9 (drawn number)
function lastChar(string _x) internal constant returns (uint8) {
bytes memory a=stringToBytes(_x);
if (a.length<=1) revert();
uint8 b=uint8(a[a.length-1])-48;
b=b%10;
if (b<0) {
LogMsg(msg.sender, "tochar: Impossible, address logged");
if (msg.sender!=owner) blacklist[msg.sender]=true;
revert();
}
return b;
}
// get the last char from a string exclude 0
function lastCharNoZero(string _x) internal constant returns (uint8) {
bytes memory a=stringToBytes(_x);
uint len=a.length;
if (len<=1) revert();
uint8 b=uint8(a[len-1])-48;
b=b%10;
while (b==0 && len>0) {
len--;
b=uint8(a[len-1])-48;
}
if (b<0) {
LogMsg(msg.sender, "tochar: Impossible, address blacklisted");
blacklist[msg.sender];
revert();
}
return b;
}
// last decimal ex:"1945671234000000000" => 4
function lastDecimal(uint256 _x) internal constant returns (uint) {
//$a=$x/(pow(10,$i));
//$b=$a%10;
uint a;
for (uint i=1;i<20;i++) {
a=(_x/(10**i)%10);
if (a>0) return a;
}
return 0;
}
// change the current play price
function setPlayPrice(uint _value, string _password ) onlyOwner external protected(_password) {
require(_value<=1000); // security, we can get crazy and offer 1000 tokens for a special promotion but no more, written in the marble of the blockchain
tokenDeliveryPlayPrice=_value;
}
// get play price
function getTotalTokenSupply() constant external returns(uint){
return tokenDeliveryPlayPrice;
}
// Change the max capitalisation token
function setMaxCap10X(uint _value, string _password ) onlyOwner external protected(_password) {
require(_value>tokenCreationCap); // we cannot set the max token capitalization lower than what it is otherwise we f*ck up the logic of the game and cannot go back
require(_value>totalTokenSupply); // of course, the new max capitalization must be higher than the current token supply, otherwise, what is the point?
totalTokenSupply=_value; // magic, creation of money
isMaxCap10XReached=false;
}
// get number of tokens available for delivery
function getMaxCap10X() constant external returns(uint){
return tokenCreationCap;
}
// Change the limit for a transaction at the crowdsale: in case we do not want people to buy too much at the time, we can limit the max value a transaction can be
function setLimitMaxCrowdsale(uint _value, string _password ) onlyOwner external protected(_password){
require(_value>=0); // of course cannot be 0
require(_value<100000 ether); // if it is >100000 there must be an error or a mistake
limitMaxCrowdsale=_value;
}
// Get the current limit
function getLimitMaxGame() constant external returns(uint){
return limitMaxGame;
}
// Change the limit for a transaction in the game : for example we have ETH in the bank but want to limit the game to bets <=2 ETH
function setLimitGame(uint _value, string _password ) onlyOwner external protected(_password){
require(_value>=0); // of course cannot be 0
require(_value<100000 ether); // if it is >100000 there must be an error or a mistake
limitMaxGame=_value;
}
// Get the current limit
function getLimitMaxCrowdsale() constant external returns(uint){
return limitMaxCrowdsale;
}
// get max the current crowdsale price
function getCrowdsalePrice( ) constant external returns(uint){
return tokenDeliveryCrowdsalePrice;
}
// change the current crowdsale status, different variant just in case, spend some gas for nothing.
function setGameStatus(bool _value,string _password ) onlyOwner external protected(_password) {
isGameOn=_value;
GameOnOff(isGameOn);
}
// get the status of the game true= game / false = crowdfunding
function getGameStatus( ) constant external returns(bool){
return isGameOn;
}
// limit the ICO to 1 transaction per address
function setIsLimited(bool _value,string _password ) onlyOwner external protected(_password) {
isLimited=_value;
}
// get limited status
function getIsLimited( ) constant external returns(bool){
return isLimited;
}
// change the current crowdsale price
function setCrowdsalePrice(uint _value,string _password ) onlyOwner external protected(_password) returns(bool){
require(_value<=10000); // crowdsale price cannot be >10,000 / ETH let's not do like SNT
tokenDeliveryCrowdsalePrice=_value;
return true;
}
// change the current contract owner
function changeContractOwner(address _value,string _password) onlyOwner external protected(_password){
owner = _value;
}
// get the current contract owner
function getContractOwner( ) constant external onlyOwner returns(address){
return owner;
}
// change the restart time period for the temp ICO
function setRestartGamePeriod(uint _value, string _password ) onlyOwner external protected(_password){
require(_value>=1 && _value<= 365); // value is in days, cannot be less than 1 day or > 365 days
restartGamePeriod=_value; // in days
}
}
| Give tokens to someone | function giveToken(address _target, uint256 _mintedAmount,string _password) external onlyOwner protected(_password) {
safeAdd(balances[_target],_mintedAmount);
safeAdd(totalTokenSupply,_mintedAmount);
}
| 12,609,344 | [
1,
43,
688,
2430,
358,
18626,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8492,
1345,
12,
2867,
389,
3299,
16,
2254,
5034,
389,
81,
474,
329,
6275,
16,
1080,
389,
3664,
13,
3903,
1338,
5541,
4750,
24899,
3664,
13,
288,
203,
3639,
4183,
986,
12,
70,
26488,
63,
67,
3299,
6487,
67,
81,
474,
329,
6275,
1769,
203,
3639,
4183,
986,
12,
4963,
1345,
3088,
1283,
16,
67,
81,
474,
329,
6275,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42/0x44d9218f00B6E13Fee4eAa3eFD24a466D905006D/sources/browser/AGOBTC_staking.sol | ------------------------------------------------------------------------ Get the AGOUSD balance of the token holder @param user the address of the token holder ------------------------------------------------------------------------ | function yourAGOUSDBalance(address user) external view returns(uint256 AGOUSDBalance){
return IERC20(AGOUSD).balanceOf(user);
}
| 16,237,090 | [
1,
29461,
968,
326,
432,
16387,
3378,
40,
11013,
434,
326,
1147,
10438,
225,
729,
326,
1758,
434,
326,
1147,
10438,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3433,
1781,
21667,
2290,
6112,
12,
2867,
729,
13,
3903,
1476,
1135,
12,
11890,
5034,
432,
16387,
3378,
2290,
6112,
15329,
203,
3639,
327,
467,
654,
39,
3462,
12,
1781,
21667,
40,
2934,
12296,
951,
12,
1355,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0xbF4A89EC7DcF405289711BB19a37F5E94769e15B/sources/contracts/CrowdFunding.sol | Check Fund is success or not | function isFundSuccess(uint256 _id) public view returns (bool) {
Campaign storage campaign = campaigns[_id];
return campaign.amountCollected >= campaign.target;
}
| 3,800,796 | [
1,
1564,
478,
1074,
353,
2216,
578,
486,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
17646,
1074,
4510,
12,
11890,
5034,
389,
350,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
17820,
2502,
8965,
273,
8965,
87,
63,
67,
350,
15533,
203,
3639,
327,
8965,
18,
8949,
10808,
329,
1545,
8965,
18,
3299,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.23;
// File: contracts/ERC223.sol
/**
* @title Interface for an ERC223 Contract
* @author Amr Gawish <[email protected]>
* @dev Only one method is unique to contracts `transfer(address _to, uint _value, bytes _data)`
* @notice The interface has been stripped to its unique methods to prevent duplicating methods with ERC20 interface
*/
interface ERC223 {
function transfer(address _to, uint _value, bytes _data) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
// File: contracts/ERC223ReceivingContract.sol
/**
* @title Contract that will work with ERC223 tokens.
*/
contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/OperatorManaged.sol
// Simple JSE Operator management contract
contract OperatorManaged is Ownable {
address public operatorAddress;
address public adminAddress;
event AdminAddressChanged(address indexed _newAddress);
event OperatorAddressChanged(address indexed _newAddress);
constructor() public
Ownable()
{
adminAddress = msg.sender;
}
modifier onlyAdmin() {
require(isAdmin(msg.sender));
_;
}
modifier onlyAdminOrOperator() {
require(isAdmin(msg.sender) || isOperator(msg.sender));
_;
}
modifier onlyOwnerOrAdmin() {
require(isOwner(msg.sender) || isAdmin(msg.sender));
_;
}
modifier onlyOperator() {
require(isOperator(msg.sender));
_;
}
function isAdmin(address _address) internal view returns (bool) {
return (adminAddress != address(0) && _address == adminAddress);
}
function isOperator(address _address) internal view returns (bool) {
return (operatorAddress != address(0) && _address == operatorAddress);
}
function isOwner(address _address) internal view returns (bool) {
return (owner != address(0) && _address == owner);
}
function isOwnerOrOperator(address _address) internal view returns (bool) {
return (isOwner(_address) || isOperator(_address));
}
// Owner and Admin can change the admin address. Address can also be set to 0 to 'disable' it.
function setAdminAddress(address _adminAddress) external onlyOwnerOrAdmin returns (bool) {
require(_adminAddress != owner);
require(_adminAddress != address(this));
require(!isOperator(_adminAddress));
adminAddress = _adminAddress;
emit AdminAddressChanged(_adminAddress);
return true;
}
// Owner and Admin can change the operations address. Address can also be set to 0 to 'disable' it.
function setOperatorAddress(address _operatorAddress) external onlyOwnerOrAdmin returns (bool) {
require(_operatorAddress != owner);
require(_operatorAddress != address(this));
require(!isAdmin(_operatorAddress));
operatorAddress = _operatorAddress;
emit OperatorAddressChanged(_operatorAddress);
return true;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20//MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: contracts/JSEToken.sol
/**
* @title Main Token Contract for JSE Coin
* @author Amr Gawish <[email protected]>
* @dev This Token is the Mintable and Burnable to allow variety of actions to be done by users.
* @dev It also complies with both ERC20 and ERC223.
* @notice Trying to use JSE Token to Contracts that doesn't accept tokens and doesn't have tokenFallback function will fail, and all contracts
* must comply to ERC223 compliance.
*/
contract JSEToken is ERC223, BurnableToken, Ownable, MintableToken, OperatorManaged {
event Finalized();
string public name = "JSE Token";
string public symbol = "JSE";
uint public decimals = 18;
uint public initialSupply = 10000000000 * (10 ** decimals); //10,000,000,000 aka 10 billion
bool public finalized;
constructor() OperatorManaged() public {
totalSupply_ = initialSupply;
balances[msg.sender] = initialSupply;
emit Transfer(0x0, msg.sender, initialSupply);
}
// Implementation of the standard transferFrom method that takes into account the finalize flag.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
checkTransferAllowed(msg.sender, _to);
return super.transferFrom(_from, _to, _value);
}
function checkTransferAllowed(address _sender, address _to) private view {
if (finalized) {
// Everybody should be ok to transfer once the token is finalized.
return;
}
// Owner and Ops are allowed to transfer tokens before the sale is finalized.
// This allows the tokens to move from the TokenSale contract to a beneficiary.
// We also allow someone to send tokens back to the owner. This is useful among other
// cases, for the Trustee to transfer unlocked tokens back to the owner (reclaimTokens).
require(isOwnerOrOperator(_sender) || _to == owner);
}
// Implementation of the standard transfer method that takes into account the finalize flag.
function transfer(address _to, uint256 _value) public returns (bool success) {
checkTransferAllowed(msg.sender, _to);
return super.transfer(_to, _value);
}
/**
* @dev transfer token for a specified contract address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data Additional Data sent to the contract.
*/
function transfer(address _to, uint _value, bytes _data) external returns (bool) {
checkTransferAllowed(msg.sender, _to);
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(isContract(_to));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
ERC223ReceivingContract erc223Contract = ERC223ReceivingContract(_to);
erc223Contract.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Owner can transfer out any accidentally sent ERC20 tokens
*/
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
function isContract(address _addr) private view returns (bool) {
uint codeSize;
/* solium-disable-next-line */
assembly {
codeSize := extcodesize(_addr)
}
return codeSize > 0;
}
// Finalize method marks the point where token transfers are finally allowed for everybody.
function finalize() external onlyAdmin returns (bool success) {
require(!finalized);
finalized = true;
emit Finalized();
return true;
}
} | Owner and Admin can change the operations address. Address can also be set to 0 to 'disable' it. | function setOperatorAddress(address _operatorAddress) external onlyOwnerOrAdmin returns (bool) {
require(_operatorAddress != owner);
require(_operatorAddress != address(this));
require(!isAdmin(_operatorAddress));
operatorAddress = _operatorAddress;
emit OperatorAddressChanged(_operatorAddress);
return true;
}
| 12,963,875 | [
1,
5541,
471,
7807,
848,
2549,
326,
5295,
1758,
18,
5267,
848,
2546,
506,
444,
358,
374,
358,
296,
8394,
11,
518,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
5592,
1887,
12,
2867,
389,
9497,
1887,
13,
3903,
1338,
5541,
1162,
4446,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
9497,
1887,
480,
3410,
1769,
203,
3639,
2583,
24899,
9497,
1887,
480,
1758,
12,
2211,
10019,
203,
3639,
2583,
12,
5,
291,
4446,
24899,
9497,
1887,
10019,
203,
203,
3639,
3726,
1887,
273,
389,
9497,
1887,
31,
203,
203,
3639,
3626,
11097,
1887,
5033,
24899,
9497,
1887,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x1811b34a601D9A2d351104cd34F0DfA16a6aEFf7/sources/browser/Business_Voter.sol | _answerId is same as it`s index | function stake(address _erc20TokenAddress, uint256 _pollId, uint256 _answerId, uint256 _amount, address _userAccount) override public {
require(_amount > 0, "You can stake only positive amount");
require(isPollExists(_erc20TokenAddress, _pollId), "Poll doesn't exist");
Poll storage poll = addressToPollById[_erc20TokenAddress][_pollId];
require(poll.endTime < now, "Poll is expired");
require(isAnswerExists(poll, _answerId), "Answer doesn't exist");
Answer storage answer = poll.answers[_answerId];
if (answer.voters[_userAccount] == 0) {
answer.voterCount++;
}
answer.voters[_userAccount] += _amount;
answer.totalStaked += _amount;
}
| 8,236,000 | [
1,
67,
13490,
548,
353,
1967,
487,
518,
68,
87,
770,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
384,
911,
12,
2867,
389,
12610,
3462,
1345,
1887,
16,
2254,
5034,
389,
13835,
548,
16,
2254,
5034,
389,
13490,
548,
16,
2254,
5034,
389,
8949,
16,
1758,
389,
1355,
3032,
13,
3849,
1071,
288,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
6225,
848,
384,
911,
1338,
6895,
3844,
8863,
203,
3639,
2583,
12,
291,
19085,
4002,
24899,
12610,
3462,
1345,
1887,
16,
389,
13835,
548,
3631,
315,
19085,
3302,
1404,
1005,
8863,
203,
540,
203,
3639,
19160,
2502,
7672,
273,
1758,
774,
19085,
5132,
63,
67,
12610,
3462,
1345,
1887,
6362,
67,
13835,
548,
15533,
203,
3639,
2583,
12,
13835,
18,
409,
950,
411,
2037,
16,
315,
19085,
353,
7708,
8863,
203,
540,
203,
3639,
2583,
12,
291,
13203,
4002,
12,
13835,
16,
389,
13490,
548,
3631,
315,
13203,
3302,
1404,
1005,
8863,
203,
3639,
21019,
2502,
5803,
273,
7672,
18,
22340,
63,
67,
13490,
548,
15533,
203,
3639,
309,
261,
13490,
18,
90,
352,
414,
63,
67,
1355,
3032,
65,
422,
374,
13,
288,
203,
5411,
5803,
18,
90,
20005,
1380,
9904,
31,
203,
3639,
289,
203,
3639,
5803,
18,
90,
352,
414,
63,
67,
1355,
3032,
65,
1011,
389,
8949,
31,
203,
3639,
5803,
18,
4963,
510,
9477,
1011,
389,
8949,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad
//Contract name: ValusCrowdsale
//Balance: 0 Ether
//Verification Date: 10/13/2017
//Transacion Count: 19
// CODE STARTS HERE
pragma solidity ^0.4.17;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract IValusToken {
function mintTokens(address _to, uint256 _amount);
function totalSupply() constant returns (uint256 totalSupply);
}
contract IERC20Token {
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
}
| Owner sets new address of escrow */ | function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
| 6,431,244 | [
1,
5541,
1678,
394,
1758,
434,
2904,
492,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2549,
5049,
291,
360,
1887,
12,
2867,
389,
2704,
1887,
13,
1338,
5541,
288,
1377,
203,
1377,
22945,
360,
1887,
273,
389,
2704,
1887,
31,
203,
565,
289,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol';
/**
* @title Vault and Royalties splitter contract
* @dev Allow to specify different rightsholder and split royalties equally
between them.
*/
contract MoiVault is OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
// A list all those entitled to royalties payment
address[] public payees;
// Percent Stored in the Vaults Treasury
uint256 public vaultPercentage = 20;
/// @notice Information about our user
/// @dev userIndex > 0 for existing payees
struct UserBalance {
uint256 userIndex;
uint256 balance;
}
struct NFTDeposit {
address owner;
}
// A record of total withdrawal amounts per payee address
mapping(address => UserBalance) public balances;
// Store all active sell offers and maps them to their respective token ids
mapping(uint256 => NFTDeposit) public StoredNFT;
// Events
event StoreNFT(uint256 tokenId, address owner);
event WithdrawNFT(uint256 tokenId, address owner);
/* Inits Contract */
function initialize(address[] memory _payees) public initializer {
payees = _payees;
for (uint256 i = 0; i < payees.length; i++) {
balances[payees[i]] = UserBalance({userIndex: i + 1, balance: 0});
}
}
/// @notice Split every received payment equally between the payees and Vault Treasury
receive() external payable {
uint256 _vaultPercentage = (msg.value * vaultPercentage) / 100;
uint256 amount = msg.value - _vaultPercentage;
uint256 sharePerPayee = amount / payees.length;
for (uint256 i = 0; i < payees.length; i++) {
balances[payees[i]].balance += sharePerPayee;
}
}
/// @notice Puts a token on sale at a given price
/// @param tokenId - id of the token to sell
/// @param minPrice - minimum price at which the token can be sold
function makeSellOffer(uint256 tokenId, uint256 minPrice)
external
isDepositable(tokenId)
tokenOwnerOnly(tokenId)
{
// Create sell offer
StoredNFT[tokenId] = NFTDeposit({
owner: msg.sender
});
// Broadcast sell offer
emit StoreNFT(tokenId, msg.sender);
}
/// @notice Withdraw a sell offer
/// @param tokenId - id of the token whose sell order needs to be cancelled
function withdrawSellOffer(uint256 tokenId) external isDepositable(tokenId) {
require(StoredNFT[tokenId].owner != address(0), 'No Deposit');
require(StoredNFT[tokenId].owner == msg.sender, 'Not Owner');
// Removes the current sell offer
delete (StoredNFT[tokenId]);
// Broadcast offer withdrawal
emit WithdrawNFT(tokenId, msg.sender);
}
/// @notice Whether an adress is in our list of payees or not
/// @param user - the address to verify
/// @return true if the user is a payee, false otherwise
function _isPayee(address user) internal view returns (bool) {
return balances[user].userIndex > 0;
}
/// @notice Lets a user withdraw some of their funds
/// @param amount - the amount to withdraw
function withdraw(uint256 amount) external isPayee(msg.sender) {
require(amount > 0);
require(amount <= balances[msg.sender].balance, 'Insufficient balance');
balances[msg.sender].balance -= amount;
payable(msg.sender).transfer(amount);
}
/// @notice Lets a user withdraw all the funds available to them
function withdrawAll() external isPayee(msg.sender) {
require(balances[msg.sender].balance > 0);
uint256 balance = balances[msg.sender].balance;
balances[msg.sender].balance = 0;
payable(msg.sender).transfer(balance);
}
/// @notice Clear all balances by paying out all payees their share
function _payAll() internal {
for (uint256 i = 0; i < payees.length; i++) {
address payee = payees[i];
uint256 availableBalance = balances[payee].balance;
if (availableBalance > 0) {
balances[payee].balance = 0;
payable(payee).transfer(availableBalance);
}
}
}
/// @notice Pay all users their current balances
function payAll() external onlyOwner {
_payAll();
}
/// @notice Remove a user from the list of payees
/// @param payee - address of the user to remove
function removePayee(address payee) external onlyOwner {
// The address needs to be a payee
require(_isPayee(payee));
// First pay everybody off and clear their balances
_payAll();
// Grab the index of the payee to remove (NOTE: our userIndex
// starts at 1)
uint256 removalIndex = balances[payee].userIndex - 1;
// Move the last payee on the list in its place
payees[removalIndex] = payees[payees.length - 1];
// And removes the last entry on the array
payees.pop();
// Unless the removed payee was also the last on the list...
if (removalIndex != payees.length) {
// ... we need to update the last payee's index to its new position
balances[payees[removalIndex]].userIndex = removalIndex + 1;
}
// Set payee's userIndex to false by deleting the entry,
// effectively stripping them from their payee status
delete (balances[payee]);
}
/// @notice Add a user to the list of payees
/// @param payee - address of the user to add
function addPayee(address payee) external onlyOwner {
// The address can't already be a payee
require(!_isPayee(payee));
// First pay everybody off and clear their balances
_payAll();
// Add the new member
payees.push(payee);
balances[payee] = UserBalance(payees.length, 0);
}
/// @notice Allow to withdraw payments made in ERC20
/// @dev Will split evenly between all current payees only. Is not called
/// when payee is added or removed
/// @param token - the token to split among all current payees
function withdrawErc20(IERC20Upgradeable token) external onlyOwner {
uint256 tokenBalance = token.balanceOf(address(this));
require(tokenBalance > 0);
uint256 payeeShare = tokenBalance / payees.length;
for (uint256 i = 0; i < payees.length; i++) {
token.transfer(payees[i], payeeShare);
}
}
modifier isDepositable(uint256 tokenId) {
require(token.getApproved(tokenId) == address(this), 'Not approved');
_;
}
modifier tokenOwnerOnly(uint256 tokenId) {
require(token.ownerOf(tokenId) == msg.sender, 'Not token owner');
_;
}
modifier isPayee(address user) {
require(_isPayee(user), 'Not payee');
_;
}
}
| Store all active sell offers and maps them to their respective token ids | mapping(uint256 => NFTDeposit) public StoredNFT;
| 5,413,062 | [
1,
2257,
777,
2695,
357,
80,
28641,
471,
7565,
2182,
358,
3675,
17613,
1147,
3258,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
2874,
12,
11890,
5034,
516,
423,
4464,
758,
1724,
13,
1071,
26548,
50,
4464,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.23;
import "openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol";
import "contracts/Goods.sol";
/**
* @title Shop contract that allows self-service minting
*/
contract Shop {
uint256 constant MINT_AMOUNT = 100 ether;
uint8 constant GOODS_AMOUNT = 4;
MintableToken asobiCoin;
Goods erc721;
constructor(MintableToken _asobiCoin, Goods _erc721) public {
require(_asobiCoin != address(0));
require(_erc721 != address(0));
asobiCoin = _asobiCoin;
erc721 = _erc721;
}
/**
* @dev buy a predetermined amount of goods and asobicoin
*/
function buy() external {
asobiCoin.mint(msg.sender, MINT_AMOUNT);
for (uint256 goods; goods < GOODS_AMOUNT; goods++) {
erc721.mint(msg.sender);
}
}
}
| * @title Shop contract that allows self-service minting/ | contract Shop {
uint256 constant MINT_AMOUNT = 100 ether;
uint8 constant GOODS_AMOUNT = 4;
MintableToken asobiCoin;
Goods erc721;
constructor(MintableToken _asobiCoin, Goods _erc721) public {
require(_asobiCoin != address(0));
require(_erc721 != address(0));
asobiCoin = _asobiCoin;
erc721 = _erc721;
}
function buy() external {
asobiCoin.mint(msg.sender, MINT_AMOUNT);
for (uint256 goods; goods < GOODS_AMOUNT; goods++) {
erc721.mint(msg.sender);
}
}
function buy() external {
asobiCoin.mint(msg.sender, MINT_AMOUNT);
for (uint256 goods; goods < GOODS_AMOUNT; goods++) {
erc721.mint(msg.sender);
}
}
}
| 6,448,002 | [
1,
7189,
6835,
716,
5360,
365,
17,
3278,
312,
474,
310,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
17568,
288,
203,
203,
565,
2254,
5034,
5381,
490,
3217,
67,
2192,
51,
5321,
273,
2130,
225,
2437,
31,
203,
565,
2254,
28,
5381,
12389,
1212,
55,
67,
2192,
51,
5321,
273,
1059,
31,
203,
203,
565,
490,
474,
429,
1345,
487,
30875,
27055,
31,
203,
565,
31732,
87,
6445,
71,
27,
5340,
31,
203,
203,
565,
3885,
12,
49,
474,
429,
1345,
389,
345,
30875,
27055,
16,
31732,
87,
389,
12610,
27,
5340,
13,
1071,
288,
203,
3639,
2583,
24899,
345,
30875,
27055,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
12610,
27,
5340,
480,
1758,
12,
20,
10019,
203,
3639,
487,
30875,
27055,
273,
389,
345,
30875,
27055,
31,
203,
3639,
6445,
71,
27,
5340,
273,
389,
12610,
27,
5340,
31,
203,
565,
289,
203,
203,
565,
445,
30143,
1435,
3903,
288,
203,
3639,
487,
30875,
27055,
18,
81,
474,
12,
3576,
18,
15330,
16,
490,
3217,
67,
2192,
51,
5321,
1769,
203,
3639,
364,
261,
11890,
5034,
7494,
87,
31,
7494,
87,
411,
12389,
1212,
55,
67,
2192,
51,
5321,
31,
7494,
87,
27245,
288,
203,
5411,
6445,
71,
27,
5340,
18,
81,
474,
12,
3576,
18,
15330,
1769,
203,
3639,
289,
203,
565,
289,
203,
565,
445,
30143,
1435,
3903,
288,
203,
3639,
487,
30875,
27055,
18,
81,
474,
12,
3576,
18,
15330,
16,
490,
3217,
67,
2192,
51,
5321,
1769,
203,
3639,
364,
261,
11890,
5034,
7494,
87,
31,
7494,
87,
411,
12389,
1212,
55,
67,
2192,
51,
5321,
31,
7494,
87,
27245,
288,
203,
5411,
6445,
2
]
|
// File: @ensdomains/ens/contracts/ENS.sol
pragma solidity >=0.4.24;
interface ENS {
// 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);
// Logged when an operator is added or removed.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external;
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external;
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32);
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
pragma solidity ^0.5.0;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
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 memory data) public;
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/ethregistrar/BaseRegistrar.sol
pragma solidity >=0.4.24;
contract BaseRegistrar is IERC721, Ownable {
uint constant public GRACE_PERIOD = 90 days;
event ControllerAdded(address indexed controller);
event ControllerRemoved(address indexed controller);
event NameMigrated(uint256 indexed id, address indexed owner, uint expires);
event NameRegistered(uint256 indexed id, address indexed owner, uint expires);
event NameRenewed(uint256 indexed id, uint expires);
// The ENS registry
ENS public ens;
// The namehash of the TLD this registrar owns (eg, .eth)
bytes32 public baseNode;
// A map of addresses that are authorised to register and renew names.
mapping(address=>bool) public controllers;
// Authorises a controller, who can register and renew domains.
function addController(address controller) external;
// Revoke controller permission for an address.
function removeController(address controller) external;
// Set the resolver for the TLD this registrar manages.
function setResolver(address resolver) external;
// Returns the expiration timestamp of the specified label hash.
function nameExpires(uint256 id) external view returns(uint);
// Returns true iff the specified name is available for registration.
function available(uint256 id) public view returns(bool);
/**
* @dev Register a name.
*/
function register(uint256 id, address owner, uint duration) external returns(uint);
function renew(uint256 id, uint duration) external returns(uint);
/**
* @dev Reclaim ownership of a name in ENS, if you own it in the registrar.
*/
function reclaim(uint256 id, address owner) external;
}
// File: contracts/Resolver.sol
pragma solidity ^0.5.0;
/**
* @dev A basic interface for ENS resolvers.
*/
contract Resolver {
function supportsInterface(bytes4 interfaceID) public pure returns (bool);
function addr(bytes32 node) public view returns (address);
function setAddr(bytes32 node, address addr) public;
}
// File: contracts/RegistrarInterface.sol
pragma solidity ^0.5.0;
contract RegistrarInterface {
event OwnerChanged(bytes32 indexed label, address indexed oldOwner, address indexed newOwner);
event DomainConfigured(bytes32 indexed label);
event DomainUnlisted(bytes32 indexed label);
event NewRegistration(bytes32 indexed label, string subdomain, address indexed owner);
event RentPaid(bytes32 indexed label, string subdomain, uint amount, uint expirationDate);
// InterfaceID of these four methods is 0xc1b15f5a
function query(bytes32 label, string calldata subdomain) external view returns (string memory domain);
function register(bytes32 label, string calldata subdomain, address owner, address resolver) external payable;
function rentDue(bytes32 label, string calldata subdomain) external view returns (uint timestamp);
function payRent(bytes32 label, string calldata subdomain) external payable;
}
// File: contracts/AbstractSubdomainRegistrar.sol
pragma solidity ^0.5.0;
contract AbstractSubdomainRegistrar is RegistrarInterface {
// namehash('eth')
bytes32 constant public TLD_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae;
bool public stopped = false;
address public registrarOwner;
address public migration;
address public registrar;
ENS public ens;
modifier owner_only(bytes32 label) {
require(owner(label) == msg.sender);
_;
}
modifier not_stopped() {
require(!stopped);
_;
}
modifier registrar_owner_only() {
require(msg.sender == registrarOwner);
_;
}
event DomainTransferred(bytes32 indexed label, string name);
constructor(ENS _ens) public {
ens = _ens;
registrar = ens.owner(TLD_NODE);
registrarOwner = msg.sender;
}
function doRegistration(bytes32 node, bytes32 label, address subdomainOwner, Resolver resolver) internal {
// Get the subdomain so we can configure it
ens.setSubnodeOwner(node, label, address(this));
bytes32 subnode = keccak256(abi.encodePacked(node, label));
// Set the subdomain's resolver
ens.setResolver(subnode, address(resolver));
// Set the address record on the resolver
resolver.setAddr(subnode, subdomainOwner);
// Pass ownership of the new subdomain to the registrant
ens.setOwner(subnode, subdomainOwner);
}
function undoRegistration(bytes32 node, bytes32 label, Resolver resolver) internal {
// // Get the subdomain so we can configure it
ens.setSubnodeOwner(node, label, address(this));
bytes32 subnode = keccak256(abi.encodePacked(node, label));
// // Set the subdomain's resolver
// ens.setResolver(subnode, address(resolver));
// Set the address record back to 0x0 on the resolver
resolver.setAddr(subnode, address(0));
// Set ownership of the new subdomain to the 0x0 address
ens.setOwner(subnode, address(0));
}
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return (
(interfaceID == 0x01ffc9a7) // supportsInterface(bytes4)
|| (interfaceID == 0xc1b15f5a) // RegistrarInterface
);
}
function rentDue(bytes32 label, string calldata subdomain) external view returns (uint timestamp) {
return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
}
/**
* @dev Sets the resolver record for a name in ENS.
* @param name The name to set the resolver for.
* @param resolver The address of the resolver
*/
function setResolver(string memory name, address resolver) public owner_only(keccak256(bytes(name))) {
bytes32 label = keccak256(bytes(name));
bytes32 node = keccak256(abi.encodePacked(TLD_NODE, label));
ens.setResolver(node, resolver);
}
/**
* @dev Configures a domain for sale.
* @param name The name to configure.
*/
function configureDomain(string memory name) public {
configureDomainFor(name, msg.sender, address(0x0));
}
/**
* @dev Stops the registrar, disabling configuring of new domains.
*/
function stop() public not_stopped registrar_owner_only {
stopped = true;
}
/**
* @dev Sets the address where domains are migrated to.
* @param _migration Address of the new registrar.
*/
function setMigrationAddress(address _migration) public registrar_owner_only {
require(stopped);
migration = _migration;
}
function transferOwnership(address newOwner) public registrar_owner_only {
registrarOwner = newOwner;
}
/**
* @dev Returns information about a subdomain.
* @param label The label hash for the domain.
* @param subdomain The label for the subdomain.
* @return domain The name of the domain, or an empty string if the subdomain
* is unavailable.
*/
function query(bytes32 label, string calldata subdomain) external view returns (string memory domain);
function owner(bytes32 label) public view returns (address);
function configureDomainFor(string memory name, address payable _owner, address _transfer) public;
}
// File: contracts/EthRegistrarSubdomainRegistrar.sol
pragma solidity ^0.5.0;
/**
* @dev Implements an ENS registrar that sells subdomains on behalf of their owners.
*
* Users may register a subdomain by calling `register` with the name of the domain
* they wish to register under, and the label hash of the subdomain they want to
* register. They must also specify the new owner of the domain, and the referrer,
* who is paid an optional finder's fee. The registrar then configures a simple
* default resolver, which resolves `addr` lookups to the new owner, and sets
* the `owner` account as the owner of the subdomain in ENS.
*
* New domains may be added by calling `configureDomain`, then transferring
* ownership in the ENS registry to this contract. Ownership in the contract
* may be transferred using `transfer`, and a domain may be unlisted for sale
* using `unlistDomain`. There is (deliberately) no way to recover ownership
* in ENS once the name is transferred to this registrar.
*
* Critically, this contract does not check one key property of a listed domain:
*
* - Is the name UTS46 normalised?
*
* User applications MUST check these two elements for each domain before
* offering them to users for registration.
*
* Applications should additionally check that the domains they are offering to
* register are controlled by this registrar, since calls to `register` will
* fail if this is not the case.
*/
contract EthRegistrarSubdomainRegistrar is AbstractSubdomainRegistrar {
struct Domain {
string name;
address payable owner;
}
mapping (bytes32 => Domain) domains;
constructor(ENS ens) AbstractSubdomainRegistrar(ens) public { }
/**
* @dev owner returns the address of the account that controls a domain.
* Initially this is a null address. If the name has been
* transferred to this contract, then the internal mapping is consulted
* to determine who controls it. If the owner is not set,
* the owner of the domain in the Registrar is returned.
* @param label The label hash of the deed to check.
* @return The address owning the deed.
*/
function owner(bytes32 label) public view returns (address) {
if (domains[label].owner != address(0x0)) {
return domains[label].owner;
}
return BaseRegistrar(registrar).ownerOf(uint256(label));
}
/**
* @dev Transfers internal control of a name to a new account. Does not update
* ENS.
* @param name The name to transfer.
* @param newOwner The address of the new owner.
*/
function transfer(string memory name, address payable newOwner) public owner_only(keccak256(bytes(name))) {
bytes32 label = keccak256(bytes(name));
emit OwnerChanged(label, domains[label].owner, newOwner);
domains[label].owner = newOwner;
}
/**
* @dev Configures a domain, optionally transferring it to a new owner.
* @param name The name to configure.
* @param _owner The address to assign ownership of this domain to.
* @param _transfer The address to set as the transfer address for the name
* when the permanent registrar is replaced. Can only be set to a non-zero
* value once.
*/
function configureDomainFor(string memory name, address payable _owner, address _transfer) public owner_only(keccak256(bytes(name))) {
bytes32 label = keccak256(bytes(name));
Domain storage domain = domains[label];
if (BaseRegistrar(registrar).ownerOf(uint256(label)) != address(this)) {
BaseRegistrar(registrar).transferFrom(msg.sender, address(this), uint256(label));
BaseRegistrar(registrar).reclaim(uint256(label), address(this));
}
if (domain.owner != _owner) {
domain.owner = _owner;
}
if (keccak256(bytes(domain.name)) != label) {
// New listing
domain.name = name;
}
emit DomainConfigured(label);
}
/**
* @dev Unlists a domain
* May only be called by the owner.
* @param name The name of the domain to unlist.
*/
function unlistDomain(string memory name) public owner_only(keccak256(bytes(name))) {
bytes32 label = keccak256(bytes(name));
Domain storage domain = domains[label];
emit DomainUnlisted(label);
domain.name = "";
}
/**
* @dev Returns information about a subdomain.
* @param label The label hash for the domain.
* @param subdomain The label for the subdomain.
* @return domain The name of the domain, or an empty string if the subdomain
* is unavailable.
*/
function query(bytes32 label, string calldata subdomain) external view returns (string memory domain) {
bytes32 node = keccak256(abi.encodePacked(TLD_NODE, label));
bytes32 subnode = keccak256(abi.encodePacked(node, keccak256(bytes(subdomain))));
if (ens.owner(subnode) != address(0x0)) {
return ("");
}
Domain storage data = domains[label];
return (data.name);
}
/**
* @dev Registers a subdomain.
* @param label The label hash of the domain to register a subdomain of.
* @param subdomain The desired subdomain label.
* @param _subdomainOwner The account that should own the newly configured subdomain.
*/
function register(bytes32 label, string calldata subdomain, address _subdomainOwner, address payable referrer, address resolver) external not_stopped payable {
address subdomainOwner = _subdomainOwner;
bytes32 domainNode = keccak256(abi.encodePacked(TLD_NODE, label));
bytes32 subdomainLabel = keccak256(bytes(subdomain));
// Subdomain must not be registered already.
require(ens.owner(keccak256(abi.encodePacked(domainNode, subdomainLabel))) == address(0));
Domain storage domain = domains[label];
// Domain must be available for registration
require(keccak256(bytes(domain.name)) == label);
// TODO: Add logic here limiting minting to only NFT owners
// Register the domain
if (subdomainOwner == address(0x0)) {
subdomainOwner = msg.sender;
}
doRegistration(domainNode, subdomainLabel, subdomainOwner, Resolver(resolver));
emit NewRegistration(label, subdomain, subdomainOwner);
}
function rentDue(bytes32 label, string calldata subdomain) external view returns (uint timestamp) {
return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
}
/**
* @dev Migrates the domain to a new registrar.
* @param name The name of the domain to migrate.
*/
function migrate(string memory name) public owner_only(keccak256(bytes(name))) {
require(stopped);
require(migration != address(0x0));
bytes32 label = keccak256(bytes(name));
Domain storage domain = domains[label];
BaseRegistrar(registrar).approve(migration, uint256(label));
EthRegistrarSubdomainRegistrar(migration).configureDomainFor(
domain.name,
domain.owner,
address(0x0)
);
delete domains[label];
emit DomainTransferred(label, name);
}
function payRent(bytes32 label, string calldata subdomain) external payable {
revert();
}
}
| Get the subdomain so we can configure it Set the subdomain's resolver ens.setResolver(subnode, address(resolver)); Set the address record back to 0x0 on the resolver Set ownership of the new subdomain to the 0x0 address | function undoRegistration(bytes32 node, bytes32 label, Resolver resolver) internal {
ens.setSubnodeOwner(node, label, address(this));
bytes32 subnode = keccak256(abi.encodePacked(node, label));
resolver.setAddr(subnode, address(0));
ens.setOwner(subnode, address(0));
}
| 1,073,565 | [
1,
967,
326,
16242,
1427,
732,
848,
5068,
518,
225,
1000,
326,
16242,
1807,
5039,
19670,
18,
542,
4301,
12,
1717,
2159,
16,
1758,
12,
14122,
10019,
1000,
326,
1758,
1409,
1473,
358,
374,
92,
20,
603,
326,
5039,
1000,
23178,
434,
326,
394,
16242,
358,
326,
374,
92,
20,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
15436,
7843,
12,
3890,
1578,
756,
16,
1731,
1578,
1433,
16,
17183,
5039,
13,
2713,
288,
203,
3639,
19670,
18,
542,
1676,
2159,
5541,
12,
2159,
16,
1433,
16,
1758,
12,
2211,
10019,
203,
203,
3639,
1731,
1578,
28300,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2159,
16,
1433,
10019,
203,
203,
3639,
5039,
18,
542,
3178,
12,
1717,
2159,
16,
1758,
12,
20,
10019,
203,
203,
3639,
19670,
18,
542,
5541,
12,
1717,
2159,
16,
1758,
12,
20,
10019,
7010,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
file: Base.sol
ver: 0.2.4
updated:20-Apr-2018
author: Darryl Morris
contributors: terraflops
email: o0ragman0o AT gmail.com
An basic contract furnishing inheriting contracts with ownership, reentry
protection and safe sending functions.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
*/
pragma solidity ^0.4.18;
contract Base
{
/* Constants */
string constant public VERSION = "Base 0.2.4";
/* State Variables */
bool mutex;
address public owner;
/* Events */
event Log(string message);
event ChangedOwner(address indexed oldOwner, address indexed newOwner);
/* Modifiers */
// To throw call not made by owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// This modifier can be used on functions with external calls to
// prevent reentry attacks.
// Constraints:
// Protected functions must have only one point of exit.
// Protected functions cannot use the `return` keyword
// Protected functions return values must be through return parameters.
modifier preventReentry() {
require(!mutex);
mutex = true;
_;
delete mutex;
return;
}
// This modifier can be applied to pulic access state mutation functions
// to protect against reentry if a `mutextProtect` function is already
// on the call stack.
modifier noReentry() {
require(!mutex);
_;
}
// Same as noReentry() but intended to be overloaded
modifier canEnter() {
require(!mutex);
_;
}
/* Functions */
function Base() public { owner = msg.sender; }
function contractBalance() public constant returns(uint) {
return this.balance;
}
// Change the owner of a contract
function changeOwner(address _newOwner)
public onlyOwner returns (bool)
{
owner = _newOwner;
ChangedOwner(msg.sender, owner);
return true;
}
function safeSend(address _recipient, uint _ether)
internal
preventReentry()
returns (bool success_)
{
require(_recipient.call.value(_ether)());
success_ = true;
}
}
/* End of Base */
| / To throw call not made by owner | {
string constant public VERSION = "Base 0.2.4";
bool mutex;
address public owner;
event Log(string message);
event ChangedOwner(address indexed oldOwner, address indexed newOwner);
file: Base.sol
protection and safe sending functions.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See MIT Licence for further details.
pragma solidity ^0.4.18;
contract Base
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier preventReentry() {
require(!mutex);
mutex = true;
_;
delete mutex;
return;
}
modifier noReentry() {
require(!mutex);
_;
}
modifier canEnter() {
require(!mutex);
_;
}
function Base() public { owner = msg.sender; }
function contractBalance() public constant returns(uint) {
return this.balance;
}
function changeOwner(address _newOwner)
public onlyOwner returns (bool)
{
owner = _newOwner;
ChangedOwner(msg.sender, owner);
return true;
}
function safeSend(address _recipient, uint _ether)
internal
preventReentry()
returns (bool success_)
{
require(_recipient.call.value(_ether)());
success_ = true;
}
}
| 1,762,391 | [
1,
19,
2974,
604,
745,
486,
7165,
635,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
95,
203,
203,
565,
533,
5381,
1071,
8456,
273,
315,
2171,
374,
18,
22,
18,
24,
14432,
203,
203,
203,
565,
1426,
9020,
31,
203,
565,
1758,
1071,
3410,
31,
203,
203,
203,
565,
871,
1827,
12,
1080,
883,
1769,
203,
565,
871,
27707,
5541,
12,
2867,
8808,
1592,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
203,
768,
30,
282,
3360,
18,
18281,
203,
685,
9694,
471,
4183,
5431,
4186,
18,
203,
203,
2503,
17888,
353,
16859,
316,
326,
27370,
716,
518,
903,
506,
5301,
16,
203,
12885,
13601,
5069,
16743,
678,
985,
54,
1258,
5538,
31,
2887,
5456,
326,
23547,
341,
5399,
970,
93,
434,
203,
20969,
1792,
6856,
22879,
578,
478,
1285,
5407,
1260,
12108,
432,
20814,
2871,
19545,
30817,
18,
282,
203,
9704,
490,
1285,
511,
335,
802,
364,
9271,
3189,
18,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
24,
18,
2643,
31,
203,
203,
16351,
3360,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
5309,
426,
4099,
1435,
288,
203,
3639,
2583,
12,
5,
29946,
1769,
203,
3639,
9020,
273,
638,
31,
203,
3639,
389,
31,
203,
3639,
1430,
9020,
31,
203,
3639,
327,
31,
203,
565,
289,
203,
203,
565,
9606,
1158,
426,
4099,
1435,
288,
203,
3639,
2583,
12,
5,
29946,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
848,
10237,
1435,
288,
203,
3639,
2583,
12,
5,
29946,
1769,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./Registrar.sol";
import "./Patient.sol";
/// @title Prescription
/// @author Austin Kugler, Alixandra Taylor
/// @notice This contract represents a prescription within the system and tracks
/// fill and refill requests
contract Prescription {
struct PrescriptionInfo {
address prescriber;
uint40 ndc;
uint8 quantity;
uint8 refills;
}
bool public fillSigRequired;
bool public refillSigRequired;
address public owner;
Registrar public registrar;
PrescriptionInfo public p;
mapping(address => bool) permissioned;
constructor(address _patientContract, address _registrarAddress, uint40 _ndc, uint8 _quantity, uint8 _refills) {
owner = _patientContract;
// Set global registry contract
registrar = Registrar(_registrarAddress);
p.ndc = _ndc;
p.quantity = _quantity;
p.refills = _refills;
p.prescriber = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Prescription reverted: Requester is not owner");
_;
}
modifier onlyPrescriber() {
require(msg.sender == p.prescriber, "Prescription reverted: Requester is not prescriber");
_;
}
modifier onlyPermissioned {
require(permissioned[msg.sender] || msg.sender == p.prescriber , "Prescription reverted: Requester is not permissioned");
_;
}
/// @notice Add a new permissioned party to this prescription (i.e. Pharmacist)
function addPermissionedPrescriber(address party) external onlyOwner {
require(permissioned[party] == false, "Prescription reverted: Requester is already permissioned");
require(registrar.isPharmacy(party), "Prescription reverted: Address is not registered");
permissioned[party] = true;
}
/// @notice Remove a permissioned party to this prescription (i.e. Pharmacist)
function removePermissionedPrescriber(address party) external onlyOwner {
require(permissioned[party] == true, "Prescription reverted: Requester is not permissioned");
permissioned[party] = false;
}
/// Multi-Sig Phase 1
function requestFill() external onlyOwner {
require(!fillSigRequired, "Prescription reverted: Prescription already signed");
// Set check signature notifier
fillSigRequired = true;
}
/// Multi-Sig Phase 2 + Execution
function fillPrescription(uint8 fillCount) external onlyPermissioned {
require(fillCount <= p.refills, "Prescription reverted: Not enough refills");
p.refills -= fillCount;
// Reset check signature notifier
fillSigRequired = false;
}
/// @notice Change the number of refills on this prescription
function refillPrescription(uint8 refillCount) external onlyPrescriber {
p.refills = refillCount;
// Reset the flag
refillSigRequired = false;
}
/// @notice Request refill (currently tabbed in)
function requestRefill() external onlyPermissioned {
require(!refillSigRequired, "Prescription reverted: Refill already signed");
refillSigRequired = true;
}
}
| @notice Remove a permissioned party to this prescription (i.e. Pharmacist) | function removePermissionedPrescriber(address party) external onlyOwner {
require(permissioned[party] == true, "Prescription reverted: Requester is not permissioned");
permissioned[party] = false;
}
| 899,703 | [
1,
3288,
279,
4132,
329,
18285,
358,
333,
4075,
24136,
261,
77,
18,
73,
18,
4360,
4610,
1077,
376,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1206,
5041,
329,
12236,
71,
1533,
264,
12,
2867,
18285,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
9827,
329,
63,
21214,
65,
422,
638,
16,
315,
12236,
24136,
15226,
329,
30,
868,
21207,
353,
486,
4132,
329,
8863,
203,
203,
3639,
4132,
329,
63,
21214,
65,
273,
629,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x7917b6f2C5deC4021Ed5D0ff3e5bb27A69B2eaCf/sources/contracts/ForceMove.sol | * @notice Checks that a given ChannelData struct matches the challenge stored on chain. @dev Checks that a given ChannelData struct matches the challenge stored on chain. @param data A given ChannelData data structure. @param channelId Unique identifier for a channel./ | function _requireMatchingStorage(ChannelData memory data, bytes32 channelId) internal view {
require(
_matchesHash(data, channelStorageHashes[channelId]),
'Channel storage does not match stored version.'
);
}
| 9,354,502 | [
1,
4081,
716,
279,
864,
5307,
751,
1958,
1885,
326,
12948,
4041,
603,
2687,
18,
225,
13074,
716,
279,
864,
5307,
751,
1958,
1885,
326,
12948,
4041,
603,
2687,
18,
225,
501,
432,
864,
5307,
751,
501,
3695,
18,
225,
27709,
14584,
2756,
364,
279,
1904,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
6528,
9517,
3245,
12,
2909,
751,
3778,
501,
16,
1731,
1578,
27709,
13,
2713,
1476,
288,
203,
3639,
2583,
12,
203,
5411,
389,
8436,
2310,
12,
892,
16,
1904,
3245,
14455,
63,
4327,
548,
65,
3631,
203,
5411,
296,
2909,
2502,
1552,
486,
845,
4041,
1177,
1093,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x9909Ee7cB9dF31309ABc383AC040E16c08E28d85/sources/flashborrow.sol | @dev Initiate a flash loan | function flashBorrow(
address,
uint256 amount
) public {
bytes memory data = abi.encode(Action.NORMAL);
lender.flashLoan(IERC3156FlashBorrower(this), address(0), amount, data);
}
| 12,301,923 | [
1,
28464,
279,
9563,
28183,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
9563,
38,
15318,
12,
203,
3639,
1758,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
1071,
288,
203,
3639,
1731,
3778,
501,
273,
24126,
18,
3015,
12,
1803,
18,
15480,
1769,
203,
3639,
328,
2345,
18,
13440,
1504,
304,
12,
45,
654,
39,
23,
28946,
11353,
38,
15318,
264,
12,
2211,
3631,
1758,
12,
20,
3631,
3844,
16,
501,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.17;
pragma experimental ABIEncoderV2;
contract ProfileContract{
enum ExchangeType{ Request, Response }
enum ExchangePurpose{ AddFriend, AddDebt, DebtRotation }
struct ExchangeDetails {
uint exchangeId;
address source;
address destination;
string optionalDescription;
ExchangeType exchangeType;
uint creationDate;
}
struct Exchange{
ExchangeDetails exchangeDetails;
ExchangePurpose exchangePurpose;
Transaction transaction;
address[] approvers;
bool isApproved;
}
struct Friend{
address friendAddress;
string friendName;
}
struct Transaction {
address from;
address to;
uint amount;
uint date;
}
// Preferences preferences;
uint exchangeNum;
mapping(address => string) friendsName;
address owner;
address[] private friends;
Exchange[] private exchanges;
address[] private contracts; // == [GroupsContract(s), BinaryContract(s)]
string[] private actionsLog;
function ProfileContract() public {
owner = msg.sender;
}
// /*
// Status includes all the attributes each user has on its ProfileContract.
// We are having this method so we can update the presented attributes in one API call.
// //TODO: implement this method as soon as we implement the rest of the things.
// */
// function getMyStatus() public restricted view returns (string[] memory myStatus){
// }
// // // ActionsLog section
// // TODO implement this method as soon as we implement the rest of the things.
// // function getActionsLog() public restricted view returns(string[] memory){
// // }
// // // Groups section
// // function createGroup() public restricted{
// // }
// // function getGroups() public restricted view returns (address[] memory){
// // }
// // Exchanges section
// function getExchangeIndexFromExchangeId(uint exchangeId) public view returns (uint){
// //TODO
// }
function removeAllExchanges() public{
delete exchanges;
}
function removeExchange(uint index) public {
if (index >= exchanges.length) return;
// We run that for loop because the only way to delete
// an item in an array is to pop its last index
// so we organize the items accordingly
for (uint i = index; i<exchanges.length-1; i++){
exchanges[i] = exchanges[i+1];
}
// exchanges.pop();
delete exchanges[exchanges.length - 1];
exchanges.length--;
}
function getAllExchanges() external view returns (Exchange[] memory){
return exchanges;
}
function getExchangeUniqueId() public returns (uint){
exchangeNum += 1;
return exchangeNum;
}
function addExchangeNotRestricted(address source, address destination, string memory optionalDescription, ExchangeType exType, ExchangePurpose purpose, address[] memory approvers, bool isApproved, address sender, uint amount, address receiver) public{
// if it runs from my ProfileContract
if (source == address(0)) {
source = address(this);
} else if (destination == address(0)){
// else - if it runs from other ProfileContract
destination = address(this);
}
//TODO: check if we need the second if statement above
if (sender != address(0)){
Transaction memory transaction = Transaction({
from: sender,
to: receiver,
amount: amount,
date: block.timestamp
});
}
ExchangeDetails memory newExchangeDetails = ExchangeDetails({
exchangeId: getExchangeUniqueId(),
source: source,
destination: destination,
optionalDescription: optionalDescription,
exchangeType: exType,
creationDate: block.timestamp
});
exchangeNum++;
Exchange memory newExchange = Exchange({
exchangeDetails: newExchangeDetails,
exchangePurpose: purpose,
transaction: transaction,
approvers: approvers,
isApproved: isApproved
});
exchanges.push(newExchange);
// return newExchange;
}
// I run for my own ProfileContract
function addExchange(address source, address destination, string memory optionalDescription, ExchangeType exType, ExchangePurpose purpose, address[] memory approvers, bool isApproved, address sender, uint amount, address receiver) public returns (Exchange memory) {
// source == address(0), destination == givenDestination
addExchangeNotRestricted(source, destination, optionalDescription,exType,purpose,approvers,isApproved, sender, amount, receiver);
}
// Friends functions
// I run from other's ProfileContract
function addFriendRequestNotRestricted(address source) public{
// Note: Actor A calls Actor_B's_addFriendRequest method in order to add
// their (Actor A's) friend request on Actor_B's exchangesList.
// No actor runs this method for themselves.
// addExchange automatically assigns source field as this contract address.
// Note: the 'new address[](0)' means we send 0 approvers for a friend request.
addExchangeNotRestricted(source, address(0), "addFriendRequest", ExchangeType.Request, ExchangePurpose.AddFriend, new address[](0), false, address(0), 0, address(0));
}
// I run for my own ProfileContract
function addFriendRequest(address destination) public{
// addExchange(source=address(0), destination=givenDestination,...)
addExchange(address(0), destination, "addFriendRequest", ExchangeType.Request, ExchangePurpose.AddFriend, new address[](0), false, address(0), 0, address(0));
}
// I run for my own ProfileContract
function confirmFriendRequest(uint friendExchangeIndex) public{
Exchange memory exchangeToConfirm = exchanges[friendExchangeIndex];
friends.push(exchangeToConfirm.exchangeDetails.destination);
removeExchange(friendExchangeIndex);
}
// I run from other's ProfileContract
function confirmFriendRequestNotRestricted(uint friendExchangeIndex) public {
Exchange memory exchangeToConfirm = exchanges[friendExchangeIndex];
friends.push(exchangeToConfirm.exchangeDetails.source);
removeExchange(friendExchangeIndex);
}
// function removeFriend(address friend) public restricted isAFriend(friend) {
// }
// for testing only
function removeAllFriends() public {
delete friends;
}
function getFriends() public view returns (address[] memory) {
return friends;
}
// function getFriendName(address friend) public view restricted returns (string memory name) {
// return "TODO";
// }
/////////////////////////////////////////////////////////////////////////////////////
// I run from other's ProfileContract
function addDebtRequestNotRestricted(address source, address sender, uint amount, address receiver) public{
// Note: Actor A calls Actor_B's_addDebtRequest method in order to add
// their (Actor A's) Debt request on Actor_B's exchangesList.
// No actor runs this method for themselves.
// addExchange automatically assigns source field as this contract address.
// Note: the 'new address[](0)' means we send 0 approvers for a Debt request.
addExchangeNotRestricted(source, address(0), "addDebtRequest", ExchangeType.Request, ExchangePurpose.AddDebt, new address[](0), false, sender, amount, receiver);
}
// I run for my own ProfileContract
function addDebtRequest(address destination, address sender, uint amount, address receiver) public{
// addExchange(source=address(0), destination=givenDestination,...)
addExchange(address(0), destination, "addDebtRequest", ExchangeType.Request, ExchangePurpose.AddDebt, new address[](0), false, sender, amount, receiver);
}
// I run for my own ProfileContract
function confirmDebtRequest(uint debtExchangeIndex) public{
// We first check on App.js if such a contract exist.
// If it is not, we create one (using a solidity method written here)
// If it is, we just addATransaction using the contract reference.
// Then we continue to the following:
// Exchange memory exchangeToConfirm = exchanges[debtExchangeIndex];
removeExchange(debtExchangeIndex);
// We do not need to push the new contract to contracts[] here as the createBinaryContract handles it
}
function getLastContract() public view returns (address){
return contracts[contracts.length -1];
}
function getZeroAddress() public view returns (address){
return address(0);
}
// I run from other's ProfileContract
function confirmDebtRequestNotRestricted(uint debtExchangeIndex, address binContractAddress) public {
// If we just deployed a binaryContract we send it's address (on App.js), else we send address(0)
// To send an address(0) we can use the getZeroAddress I implemented here
if (binContractAddress != address(0)){ // it means we just deployed a binContract
contracts.push(binContractAddress);
}
// Exchange memory exchangeToConfirm = exchanges[debtExchangeIndex];
removeExchange(debtExchangeIndex);
}
/////////////////////////////////////////////////////////////////////////////////////
function createBinaryContract(address sender, uint amount, address receiver) public {
address newBinaryContract = new BinaryContract(sender, amount, receiver);
contracts.push(newBinaryContract);
}
function getContracts() public view returns (address[] memory){
return contracts;
}
// For testing only!!!!!!!!!
function removeContracts() public {
delete contracts;
}
// modifier restricted(){
// require(msg.sender == owner);
// _;
// }
modifier isAFriend(address person){
bool isAFriendbool = false;
for (uint i=0; i<friends.length; i++) {
if (friends[i] == person){
isAFriendbool = true;
}
}
require(isAFriendbool == true);
_;
}
}
contract BinaryContract{
struct Transaction {
address from;
address to;
uint amount;
uint date;
}
// We have that struct as it stores the current contract status (the "sum" of all the contract's transactions)
// It saves power/money for the caller - every time a user adds a debt - it changes the ContractDebt as well
struct ContractDebt{
address debtor;
address creditor;
uint amountOwned;
}
uint creationDate;
uint validityInDays;
bool isValid = true;
address playerOne;
address playerTwo;
ContractDebt currentDebt;
Transaction[] binContractTransactionsLog;
// E.g. BinaryContract(player1, 2, player2) == deploy a new contract, where player 1 owes 2 shekels to player 2
function BinaryContract(address providedCreditor, uint amount, address providedDebtor) public{
playerOne = providedDebtor;
playerTwo = providedCreditor;
addTransaction(providedCreditor, amount, providedDebtor);
}
function addTransaction (address sender, uint amount, address receiver) public {
Transaction memory transaction = Transaction({
from: sender,
to: receiver,
amount: amount,
date: block.timestamp
});
binContractTransactionsLog.push(transaction);
updateContractDebt(sender, amount, receiver);
}
function updateContractDebt (address sender, uint amount, address receiver) public {
if(binContractTransactionsLog.length != 1){ // in the constructor we just pushed the only transaction
if (currentDebt.debtor != sender){ // means the debtor now in a bigger debt
currentDebt.amountOwned += amount;
} else { // means the debtor is the sender
if (amount > currentDebt.amountOwned){
updateDebtor(receiver);
updateCreditor(sender);
currentDebt.amountOwned = amount - currentDebt.amountOwned;
} else{
currentDebt.amountOwned -= amount;
}
}
} else {
currentDebt.debtor = receiver;
currentDebt.creditor = sender;
currentDebt.amountOwned = amount;
}
}
function updateDebtor(address newDebtor) public {
currentDebt.debtor = newDebtor;
}
function updateCreditor(address newCreditor) public {
currentDebt.creditor = newCreditor;
}
function getCurrentDebtorAddress() public view returns(address){
return currentDebt.debtor;
}
// not implemented yet
//// function getCurrentDebtorName() public view returns(string memory){
//// //return currentDebt.debtor name
//// }
function getCurrentCreditorAddress() public view returns(address){
return currentDebt.creditor;
}
// not implemented yet
//// function getCurrentCreditorName() public view returns(string memory){
//// //return currentDebt.creditor name
//// }
function getCurrentDebtAmount() public view returns(uint){
return currentDebt.amountOwned;
}
function getCurrentDebt() public view returns(ContractDebt){
return currentDebt;
}
modifier ifValid(){
if (block.timestamp > creationDate + validityInDays * 1 days){
isValid = false;
}
require(isValid);
_;
}
} | For testing only!!!!!!!!! | function removeContracts() public {
delete contracts;
}
| 12,723,510 | [
1,
1290,
7769,
1338,
23045,
23045,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1206,
20723,
1435,
1071,
288,
203,
3639,
1430,
20092,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.16;
import "./ExternStateToken.sol";
import "./TokenState.sol";
import "./MixinResolver.sol";
// import "./SupplySchedule.sol";
import "./Synth.sol";
// import "./interfaces/ISynthetixState.sol";
// import "./interfaces/IExchangeRates.sol";
// import "./interfaces/ISynthetixEscrow.sol";
// import "./interfaces/IFeePool.sol";
// import "./interfaces/IRewardsDistribution.sol";
// import "./interfaces/IExchanger.sol";
import "./interfaces/IIssuer.sol";
// import "./interfaces/IEtherCollateral.sol";
/**
* @title Synthetix ERC20 contract.
* @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances,
* but it also computes the quantity of fees each synthetix holder is entitled to.
*/
contract Synthetix is ExternStateToken, MixinResolver {
// ========== STATE VARIABLES ==========
// Available Synths which can be used with the system
Synth[] public availableSynths;
mapping(bytes32 => Synth) public synths;
mapping(address => bytes32) public synthsByAddress;
string constant TOKEN_NAME = "Synthetix Network Token";
string constant TOKEN_SYMBOL = "SNX";
uint8 constant DECIMALS = 18;
bytes32 constant sUSD = "sUSD";
// ========== CONSTRUCTOR ==========
/**
* @dev Constructor
* @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol
* @param _tokenState Address of the external immutable contract containing token balances.
* @param _owner The owner of this contract.
* @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated)
* @param _resolver The address of the Synthetix Address Resolver
*/
constructor(address payable _proxy, TokenState _tokenState, address _owner, uint _totalSupply, address _resolver)
public
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner)
MixinResolver(_owner, _resolver)
{}
/* ========== VIEWS ========== */
function exchanger() internal view returns (IExchanger) {
return IExchanger(resolver.requireAndGetAddress("Exchanger", "Missing Exchanger address"));
}
// function etherCollateral() internal view returns (IEtherCollateral) {
// return IEtherCollateral(resolver.requireAndGetAddress("EtherCollateral", "Missing EtherCollateral address"));
// }
function issuer() internal view returns (IIssuer) {
return IIssuer(resolver.requireAndGetAddress("Issuer", "Missing Issuer address"));
}
// function synthetixState() internal view returns (ISynthetixState) {
// return ISynthetixState(resolver.requireAndGetAddress("SynthetixState", "Missing SynthetixState address"));
// }
// function exchangeRates() internal view returns (IExchangeRates) {
// return IExchangeRates(resolver.requireAndGetAddress("ExchangeRates", "Missing ExchangeRates address"));
// }
// function feePool() internal view returns (IFeePool) {
// return IFeePool(resolver.requireAndGetAddress("FeePool", "Missing FeePool address"));
// }
// function supplySchedule() internal view returns (SupplySchedule) {
// return SupplySchedule(resolver.requireAndGetAddress("SupplySchedule", "Missing SupplySchedule address"));
// }
// function rewardEscrow() internal view returns (ISynthetixEscrow) {
// return ISynthetixEscrow(resolver.requireAndGetAddress("RewardEscrow", "Missing RewardEscrow address"));
// }
// function synthetixEscrow() internal view returns (ISynthetixEscrow) {
// return ISynthetixEscrow(resolver.requireAndGetAddress("SynthetixEscrow", "Missing SynthetixEscrow address"));
// }
// function rewardsDistribution() internal view returns (IRewardsDistribution) {
// return
// IRewardsDistribution(
// resolver.requireAndGetAddress("RewardsDistribution", "Missing RewardsDistribution address")
// );
// }
// /**
// * @notice Total amount of synths issued by the system, priced in currencyKey
// * @param currencyKey The currency to value the synths in
// */
// function _totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) internal view returns (uint) {
// IExchangeRates exRates = exchangeRates();
// uint total = 0;
// uint currencyRate = exRates.rateForCurrency(currencyKey);
// (uint[] memory rates, bool anyRateStale) = exRates.ratesAndStaleForCurrencies(availableCurrencyKeys());
// require(!anyRateStale, "Rates are stale");
// for (uint i = 0; i < availableSynths.length; i++) {
// // What's the total issued value of that synth in the destination currency?
// // Note: We're not using exchangeRates().effectiveValue() because we don't want to go get the
// // rate for the destination currency and check if it's stale repeatedly on every
// // iteration of the loop
// uint totalSynths = availableSynths[i].totalSupply();
// // minus total issued synths from Ether Collateral from sETH.totalSupply()
// if (excludeEtherCollateral && availableSynths[i] == synths["sETH"]) {
// totalSynths = totalSynths.sub(etherCollateral().totalIssuedSynths());
// }
// uint synthValue = totalSynths.multiplyDecimalRound(rates[i]);
// total = total.add(synthValue);
// }
// return total.divideDecimalRound(currencyRate);
// }
// /**
// * @notice Total amount of synths issued by the system priced in currencyKey
// * @param currencyKey The currency to value the synths in
// */
// function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) {
// return _totalIssuedSynths(currencyKey, false);
// }
// /**
// * @notice Total amount of synths issued by the system priced in currencyKey, excluding ether collateral
// * @param currencyKey The currency to value the synths in
// */
// function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) public view returns (uint) {
// return _totalIssuedSynths(currencyKey, true);
// }
/**
* @notice Returns the currencyKeys of availableSynths for rate checking
*/
function availableCurrencyKeys() public view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availableSynths.length);
for (uint i = 0; i < availableSynths.length; i++) {
currencyKeys[i] = synthsByAddress[address(availableSynths[i])];
}
return currencyKeys;
}
/**
* @notice Returns the count of available synths in the system, which you can use to iterate availableSynths
*/
function availableSynthCount() public view returns (uint) {
return availableSynths.length;
}
// function isWaitingPeriod(bytes32 currencyKey) external view returns (bool) {
// return exchanger().maxSecsLeftInWaitingPeriod(messageSender, currencyKey) > 0;
// }
// ========== MUTATIVE FUNCTIONS ==========
/**
* @notice Add an associated Synth contract to the Synthetix system
* @dev Only the contract owner may call this.
*/
function addSynth(Synth synth) external optionalProxy_onlyOwner {
bytes32 currencyKey = synth.currencyKey();
require(synths[currencyKey] == Synth(0), "Synth already exists");
require(synthsByAddress[address(synth)] == bytes32(0), "Synth address already exists");
availableSynths.push(synth);
synths[currencyKey] = synth;
synthsByAddress[address(synth)] = currencyKey;
}
// /**
// * @notice Remove an associated Synth contract from the Synthetix system
// * @dev Only the contract owner may call this.
// */
// function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner {
// require(address(synths[currencyKey]) != address(0), "Synth does not exist");
// require(synths[currencyKey].totalSupply() == 0, "Synth supply exists");
// require(currencyKey != sUSD, "Cannot remove synth");
// // Save the address we're removing for emitting the event at the end.
// address synthToRemove = address(synths[currencyKey]);
// // Remove the synth from the availableSynths array.
// for (uint i = 0; i < availableSynths.length; i++) {
// if (address(availableSynths[i]) == synthToRemove) {
// delete availableSynths[i];
// // Copy the last synth into the place of the one we just deleted
// // If there's only one synth, this is synths[0] = synths[0].
// // If we're deleting the last one, it's also a NOOP in the same way.
// availableSynths[i] = availableSynths[availableSynths.length - 1];
// // Decrease the size of the array by one.
// availableSynths.length--;
// break;
// }
// }
// // And remove it from the synths mapping
// delete synthsByAddress[address(synths[currencyKey])];
// delete synths[currencyKey];
// // Note: No event here as Synthetix contract exceeds max contract size
// // with these events, and it's unlikely people will need to
// // track these events specifically.
// }
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value) public optionalProxy returns (bool) {
// Ensure they're not trying to exceed their staked SNX amount
// require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // TODO OPTIMISM UNCOMMENT
// Perform the transfer: if there is a problem an exception will be thrown in this call.
// _transfer_byProxy(messageSender, to, value);
return true;
}
// /**
// * @notice ERC20 transferFrom function.
// */
// function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) {
// // Ensure they're not trying to exceed their locked amount
// require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX");
// // Perform the transfer: if there is a problem,
// // an exception will be thrown in this call.
// return _transferFrom_byProxy(messageSender, from, to, value);
// }
function issueSynths(uint amount) external optionalProxy {
return issuer().issueSynths(messageSender, amount);
}
// function issueMaxSynths() external optionalProxy {
// return issuer().issueMaxSynths(messageSender);
// }
// function burnSynths(uint amount) external optionalProxy {
// return issuer().burnSynths(messageSender, amount);
// }
// function burnSynthsToTarget() external optionalProxy {
// return issuer().burnSynthsToTarget(messageSender);
// }
function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
external
optionalProxy
returns (uint amountReceived)
{
return exchanger().exchange(messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender);
}
function settle(bytes32 currencyKey) external optionalProxy returns (uint reclaimed, uint refunded) {
return exchanger().settle(messageSender, currencyKey);
}
// // ========== Issuance/Burning ==========
// /**
// * @notice The maximum synths an issuer can issue against their total synthetix quantity.
// * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue.
// */
// function maxIssuableSynths(address _issuer)
// public
// view
// returns (
// // We don't need to check stale rates here as effectiveValue will do it for us.
// uint
// )
// {
// // What is the value of their SNX balance in the destination currency?
// uint destinationValue = exchangeRates().effectiveValue("SNX", collateral(_issuer), sUSD);
// // They're allowed to issue up to issuanceRatio of that value
// return destinationValue.multiplyDecimal(synthetixState().issuanceRatio());
// }
// /*
// * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time
// * as the value of the underlying Synthetix asset changes,
// * e.g. based on an issuance ratio of 20%. if a user issues their maximum available
// * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value
// * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are
// * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by
// * altering the amount of fees they're able to claim from the system.
// */
// function collateralisationRatio(address _issuer) public view returns (uint) {
// uint totalOwnedSynthetix = collateral(_issuer);
// if (totalOwnedSynthetix == 0) return 0;
// uint debtBalance = debtBalanceOf(_issuer, "SNX");
// return debtBalance.divideDecimalRound(totalOwnedSynthetix);
// }
// /**
// * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function
// * will tell you how many synths a user has to give back to the system in order to unlock their original
// * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price
// * the debt in sUSD, or any other synth you wish.
// */
// function debtBalanceOf(address _issuer, bytes32 currencyKey)
// public
// view
// returns (
// // Don't need to check for stale rates here because totalIssuedSynths will do it for us
// uint
// )
// {
// ISynthetixState state = synthetixState();
// // What was their initial debt ownership?
// (uint initialDebtOwnership, ) = state.issuanceData(_issuer);
// // If it's zero, they haven't issued, and they have no debt.
// if (initialDebtOwnership == 0) return 0;
// (uint debtBalance, ) = debtBalanceOfAndTotalDebt(_issuer, currencyKey);
// return debtBalance;
// }
// function debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey)
// public
// view
// returns (
// uint debtBalance,
// uint totalSystemValue
// )
// {
// ISynthetixState state = synthetixState();
// // What was their initial debt ownership?
// uint initialDebtOwnership;
// uint debtEntryIndex;
// (initialDebtOwnership, debtEntryIndex) = state.issuanceData(_issuer);
// // What's the total value of the system excluding ETH backed synths in their requested currency?
// totalSystemValue = totalIssuedSynthsExcludeEtherCollateral(currencyKey);
// // If it's zero, they haven't issued, and they have no debt.
// if (initialDebtOwnership == 0) return (0, totalSystemValue);
// // Figure out the global debt percentage delta from when they entered the system.
// // This is a high precision integer of 27 (1e27) decimals.
// uint currentDebtOwnership = state
// .lastDebtLedgerEntry()
// .divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex))
// .multiplyDecimalRoundPrecise(initialDebtOwnership);
// // Their debt balance is their portion of the total system value.
// uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(
// currentDebtOwnership
// );
// // Convert back into 18 decimals (1e18)
// debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
// }
// /**
// * @notice The remaining synths an issuer can issue against their total synthetix balance.
// * @param _issuer The account that intends to issue
// */
// function remainingIssuableSynths(address _issuer)
// public
// view
// returns (
// // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us.
// uint maxIssuable,
// uint alreadyIssued,
// uint totalSystemDebt
// )
// {
// (alreadyIssued, totalSystemDebt) = debtBalanceOfAndTotalDebt(_issuer, sUSD);
// maxIssuable = maxIssuableSynths(_issuer);
// if (alreadyIssued >= maxIssuable) {
// maxIssuable = 0;
// } else {
// maxIssuable = maxIssuable.sub(alreadyIssued);
// }
// }
// /**
// * @notice The total SNX owned by this account, both escrowed and unescrowed,
// * against which synths can be issued.
// * This includes those already being used as collateral (locked), and those
// * available for further issuance (unlocked).
// */
// function collateral(address account) public view returns (uint) {
// uint balance = tokenState.balanceOf(account);
// if (address(synthetixEscrow()) != address(0)) {
// balance = balance.add(synthetixEscrow().balanceOf(account));
// }
// if (address(rewardEscrow()) != address(0)) {
// balance = balance.add(rewardEscrow().balanceOf(account));
// }
// return balance;
// }
// /**
// * @notice The number of SNX that are free to be transferred for an account.
// * @dev Escrowed SNX are not transferable, so they are not included
// * in this calculation.
// * @notice SNX rate not stale is checked within debtBalanceOf
// */
// function transferableSynthetix(address account)
// public
// view
// rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths
// returns (uint)
// {
// // How many SNX do they have, excluding escrow?
// // Note: We're excluding escrow here because we're interested in their transferable amount
// // and escrowed SNX are not transferable.
// uint balance = tokenState.balanceOf(account);
// // How many of those will be locked by the amount they've issued?
// // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require
// // 100 SNX to be locked in their wallet to maintain their collateralisation ratio
// // The locked synthetix value can exceed their balance.
// uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState().issuanceRatio());
// // If we exceed the balance, no SNX are transferable, otherwise the difference is.
// if (lockedSynthetixValue >= balance) {
// return 0;
// } else {
// return balance.sub(lockedSynthetixValue);
// }
// }
// /**
// * @notice Mints the inflationary SNX supply. The inflation shedule is
// * defined in the SupplySchedule contract.
// * The mint() function is publicly callable by anyone. The caller will
// receive a minter reward as specified in supplySchedule.minterReward().
// */
// function mint() external returns (bool) {
// require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set");
// SupplySchedule _supplySchedule = supplySchedule();
// IRewardsDistribution _rewardsDistribution = rewardsDistribution();
// uint supplyToMint = _supplySchedule.mintableSupply();
// require(supplyToMint > 0, "No supply is mintable");
// // record minting event before mutation to token supply
// _supplySchedule.recordMintEvent(supplyToMint);
// // Set minted SNX balance to RewardEscrow's balance
// // Minus the minterReward and set balance of minter to add reward
// uint minterReward = _supplySchedule.minterReward();
// // Get the remainder
// uint amountToDistribute = supplyToMint.sub(minterReward);
// // Set the token balance to the RewardsDistribution contract
// tokenState.setBalanceOf(address(_rewardsDistribution), tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute));
// emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute);
// // Kick off the distribution of rewards
// _rewardsDistribution.distributeRewards(amountToDistribute);
// // Assign the minters reward.
// tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
// emitTransfer(address(this), msg.sender, minterReward);
// totalSupply = totalSupply.add(supplyToMint);
// return true;
// }
// // ========== MODIFIERS ==========
// modifier rateNotStale(bytes32 currencyKey) {
// require(!exchangeRates().rateIsStale(currencyKey), "Rate stale or not a synth");
// _;
// }
modifier onlyExchanger() {
require(msg.sender == address(exchanger()), "Only the exchanger contract can invoke this function");
_;
}
// ========== EVENTS ==========
/* solium-disable */
event SynthExchange(
address indexed account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
);
bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)");
function emitSynthExchange(
address account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
) external onlyExchanger {
proxy._emit(
abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress),
2,
SYNTHEXCHANGE_SIG,
bytes32(uint256(uint160(account))),
0,
0
);
}
event ExchangeReclaim(address indexed account, bytes32 currencyKey, uint amount);
bytes32 constant EXCHANGERECLAIM_SIG = keccak256("ExchangeReclaim(address,bytes32,uint256)");
function emitExchangeReclaim(address account, bytes32 currencyKey, uint256 amount) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGERECLAIM_SIG, bytes32(uint256(uint160(account))), 0, 0);
}
event ExchangeRebate(address indexed account, bytes32 currencyKey, uint amount);
bytes32 constant EXCHANGEREBATE_SIG = keccak256("ExchangeRebate(address,bytes32,uint256)");
function emitExchangeRebate(address account, bytes32 currencyKey, uint256 amount) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGEREBATE_SIG, bytes32(uint256(uint160(account))), 0, 0);
}
/* solium-enable */
}
| * @notice ERC20 transfer function./ Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); TODO OPTIMISM UNCOMMENT Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); | function transfer(address to, uint value) public optionalProxy returns (bool) {
return true;
}
| 13,047,788 | [
1,
654,
39,
3462,
7412,
445,
18,
19,
7693,
2898,
4565,
486,
8374,
358,
9943,
3675,
384,
9477,
14204,
60,
3844,
2583,
12,
1132,
1648,
7412,
429,
10503,
451,
278,
697,
12,
2150,
12021,
3631,
315,
4515,
7412,
384,
9477,
578,
2904,
492,
329,
14204,
60,
8863,
225,
2660,
16456,
3445,
5127,
49,
5019,
12200,
11217,
326,
7412,
30,
309,
1915,
353,
279,
6199,
392,
1520,
903,
506,
6718,
316,
333,
745,
18,
389,
13866,
67,
1637,
3886,
12,
2150,
12021,
16,
358,
16,
460,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
12,
2867,
358,
16,
2254,
460,
13,
1071,
3129,
3886,
1135,
261,
6430,
13,
288,
203,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-11-14
*/
/**
*Submitted for verification at Etherscan.io on 2021-11-14
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
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) {
// 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 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;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
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;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event 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 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;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract ThunderCatsInu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public marketingAddress = payable(0xfc436ec95a1eaC71A82e514BdBf1D53CCA548C0a); // Marketing Address
address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isSniper;
address[] private _confirmedSnipers;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "ThunderCats Inu";
string private _symbol = "THUNDERCATS";
uint8 private _decimals = 9;
uint256 public _taxFee;
uint256 private _previousTaxFee = _taxFee;
uint256 private _liquidityFee;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 private _feeRate = 2;
uint256 launchTime;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
uint256 public maxTX =400000000000000e9; //30000000000000e9;
bool inSwapAndLiquify;
bool tradingOpen = false;
bool public opensellTx=true;
uint256 public _buyFee=10;
uint256 public _sellFee=10;
event SwapETHForTokens(
uint256 amountIn,
address[] path
);
event SwapTokensForETH(
uint256 amountIn,
address[] path
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
openTrading();
emit Transfer(address(0), _msgSender(), _tTotal);
}
function initContract() external onlyOwner() {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
marketingAddress = payable(marketingAddress);
}
function openTrading() internal {
_liquidityFee=10;
_taxFee=0;
tradingOpen = true;
launchTime = block.timestamp;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isSniper[to], "You have no power here!");
require(!_isSniper[msg.sender], "You have no power here!");
// buy
if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) {
require(tradingOpen, "Trading not yet enabled.");
//antibot
if (block.timestamp == launchTime) {
_isSniper[to] = true;
_confirmedSnipers.push(to);
}
}
if((from!=owner() && from!=address(uniswapV2Router)) || (to!=owner() && to!=uniswapV2Pair))
{
require(maxTX >= amount,"maxTX Amount Exceed");
}
uint256 contractTokenBalance = balanceOf(address(this));
//sell
if (!inSwapAndLiquify && tradingOpen && to == uniswapV2Pair) {
if(contractTokenBalance > 0) {
if(contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)) {
contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(100);
}
swapTokens(contractTokenBalance);
}
if(opensellTx==false)
{
revert('Sell Tx not allowed');
}
}
bool takeFee = false;
//take fee only on swaps
if ( (from==uniswapV2Pair || to==uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) {
takeFee = true;
}
_tokenTransfer(from,to,amount,takeFee);
}
function swapTokens(uint256 contractTokenBalance) private lockTheSwap {
swapTokensForEth(contractTokenBalance);
//Send to Marketing address
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
function sendETHToFee(uint256 amount) private {
marketingAddress.transfer(amount);
}
function ManualApproval() public onlyOwner
{
uint256 contractTokenBalance = balanceOf(address(this));
_approve(address(this), address(uniswapV2Router), contractTokenBalance);
}
function changeSellTx(bool _status) public onlyOwner {
opensellTx=_status;
}
function ManualswapTokens(uint256 contractTokenBalance) public onlyOwner {
// uint256 contractTokenBalance = balanceOf(address(this));
swapTokensForEth(contractTokenBalance);
//Send to Marketing address
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this), // The contract
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setBuySellFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
_buyFee=liquidityFee;
_sellFee=liquidityFee;
}
function setmaxTX(uint256 amount) external onlyOwner() {
maxTX = amount;
}
function setMarketingAddress(address _marketingAddress) external onlyOwner() {
marketingAddress = payable(_marketingAddress);
}
function transferToAddressETH(address payable recipient, uint256 amount) private {
recipient.transfer(amount);
}
function isBlacklist(address account) public view returns (bool) {
return _isSniper[account];
}
function _removeSniper(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap');
require(!_isSniper[account], "Account is already blacklisted");
_isSniper[account] = true;
_confirmedSnipers.push(account);
}
function _amnestySniper(address account) external onlyOwner() {
require(_isSniper[account], "Account is not blacklisted");
for (uint256 i = 0; i < _confirmedSnipers.length; i++) {
if (_confirmedSnipers[i] == account) {
_confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1];
_isSniper[account] = false;
_confirmedSnipers.pop();
break;
}
}
}
function setFeeRate(uint256 rate) external onlyOwner() {
_feeRate = rate;
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
} | buyantibottake fee only on swaps | function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isSniper[to], "You have no power here!");
require(!_isSniper[msg.sender], "You have no power here!");
if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) {
require(tradingOpen, "Trading not yet enabled.");
if (block.timestamp == launchTime) {
_isSniper[to] = true;
_confirmedSnipers.push(to);
}
}
if((from!=owner() && from!=address(uniswapV2Router)) || (to!=owner() && to!=uniswapV2Pair))
{
require(maxTX >= amount,"maxTX Amount Exceed");
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && tradingOpen && to == uniswapV2Pair) {
if(contractTokenBalance > 0) {
if(contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)) {
contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(100);
}
swapTokens(contractTokenBalance);
}
if(opensellTx==false)
{
revert('Sell Tx not allowed');
}
}
bool takeFee = false;
if ( (from==uniswapV2Pair || to==uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) {
takeFee = true;
}
_tokenTransfer(from,to,amount,takeFee);
}
| 2,126,243 | [
1,
70,
9835,
970,
495,
352,
22188,
14036,
1338,
603,
1352,
6679,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
3639,
2583,
12,
5,
67,
291,
10461,
77,
457,
63,
869,
6487,
315,
6225,
1240,
1158,
7212,
2674,
4442,
1769,
203,
3639,
2583,
12,
5,
67,
291,
10461,
77,
457,
63,
3576,
18,
15330,
6487,
315,
6225,
1240,
1158,
7212,
2674,
4442,
1769,
203,
203,
3639,
203,
3639,
309,
12,
2080,
422,
640,
291,
91,
438,
58,
22,
4154,
597,
358,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
13,
597,
401,
67,
291,
16461,
1265,
14667,
63,
869,
5717,
288,
203,
5411,
2583,
12,
313,
14968,
3678,
16,
315,
1609,
7459,
486,
4671,
3696,
1199,
1769,
203,
2398,
203,
5411,
309,
261,
2629,
18,
5508,
422,
8037,
950,
13,
288,
203,
7734,
389,
291,
10461,
77,
457,
63,
869,
65,
273,
638,
31,
203,
7734,
389,
21606,
10461,
625,
414,
18,
6206,
12,
869,
1769,
203,
5411,
289,
203,
3639,
289,
203,
540,
203,
540,
309,
12443,
2080,
5,
33,
8443,
1435,
597,
628,
5,
33,
2867,
12,
318,
291,
91,
438,
58,
22,
8259,
3719,
2
]
|
// File: @openzeppelin/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/proxy/UpgradeableProxy.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// File: contracts/UpgradeableExtension.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This contract implements an upgradeable extension. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableExtension is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor() public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
newImplementation == address(0x0) || Address.isContract(newImplementation),
"UpgradeableExtension: new implementation must be 0x0 or a contract"
);
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address62 {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address62 for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address62 for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: openzeppelin-solidity/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: contracts/ReentrancyGuardPausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Reuse openzeppelin's ReentrancyGuard with Pausable feature
*/
contract ReentrancyGuardPausable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private constant _PAUSEDV1 = 4;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrantAndUnpaused(uint256 version) {
{
uint256 status = _status;
// On the first call to nonReentrant, _notEntered will be true
require((status & (1 << (version + 1))) == 0, "ReentrancyGuard: paused");
require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = status ^ _ENTERED;
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status ^= _ENTERED;
}
modifier nonReentrantAndUnpausedV1() {
{
uint256 status = _status;
// On the first call to nonReentrant, _notEntered will be true
require((status & _PAUSEDV1) == 0, "ReentrancyGuard: paused");
require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = status ^ _ENTERED;
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status ^= _ENTERED;
}
function _pause(uint256 flag) internal {
_status |= flag;
}
function _unpause(uint256 flag) internal {
_status &= ~flag;
}
}
// File: contracts/YERC20.sol
pragma solidity ^0.6.0;
/* TODO: Actually methods are public instead of external */
interface YERC20 is IERC20 {
function getPricePerFullShare() external view returns (uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
}
// File: contracts/SmoothyV1.sol
pragma solidity ^0.6.0;
contract SmoothyV1 is ReentrancyGuardPausable, ERC20, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant W_ONE = 1e18;
uint256 constant U256_1 = 1;
uint256 constant SWAP_FEE_MAX = 2e17;
uint256 constant REDEEM_FEE_MAX = 2e17;
uint256 constant ADMIN_FEE_PCT_MAX = 5e17;
/** @dev Fee collector of the contract */
address public _rewardCollector;
// Using mapping instead of array to save gas
mapping(uint256 => uint256) public _tokenInfos;
mapping(uint256 => address) public _yTokenAddresses;
// Best estimate of token balance in y pool.
// Save the gas cost of calling yToken to evaluate balanceInToken.
mapping(uint256 => uint256) public _yBalances;
/*
* _totalBalance is expected to >= sum(_getBalance()'s), where the diff is the admin fee
* collected by _collectReward().
*/
uint256 public _totalBalance;
uint256 public _swapFee = 4e14; // 1E18 means 100%
uint256 public _redeemFee = 0; // 1E18 means 100%
uint256 public _adminFeePct = 0; // % of swap/redeem fee to admin
uint256 public _adminInterestPct = 0; // % of interest to admins
uint256 public _ntokens;
uint256 constant YENABLE_OFF = 40;
uint256 constant DECM_OFF = 41;
uint256 constant TID_OFF = 46;
event Swap(
address indexed buyer,
uint256 bTokenIdIn,
uint256 bTokenIdOut,
uint256 inAmount,
uint256 outAmount
);
event SwapAll(
address indexed provider,
uint256[] amounts,
uint256 inOutFlag,
uint256 sTokenMintedOrBurned
);
event Mint(
address indexed provider,
uint256 inAmounts,
uint256 sTokenMinted
);
event Redeem(
address indexed provider,
uint256 bTokenAmount,
uint256 sTokenBurn
);
constructor (
address[] memory tokens,
address[] memory yTokens,
uint256[] memory decMultipliers,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
public
ERC20("Smoothy LP Token", "syUSD")
{
require(tokens.length == yTokens.length, "tokens and ytokens must have the same length");
require(
tokens.length == decMultipliers.length,
"tokens and decMultipliers must have the same length"
);
require(
tokens.length == hardWeights.length,
"incorrect hard wt. len"
);
require(
tokens.length == softWeights.length,
"incorrect soft wt. len"
);
_rewardCollector = msg.sender;
for (uint8 i = 0; i < tokens.length; i++) {
uint256 info = uint256(tokens[i]);
require(hardWeights[i] >= softWeights[i], "hard wt. must >= soft wt.");
require(hardWeights[i] <= W_ONE, "hard wt. must <= 1e18");
info = _setHardWeight(info, hardWeights[i]);
info = _setSoftWeight(info, softWeights[i]);
info = _setDecimalMultiplier(info, decMultipliers[i]);
info = _setTID(info, i);
_yTokenAddresses[i] = yTokens[i];
// _balances[i] = 0; // no need to set
if (yTokens[i] != address(0x0)) {
info = _setYEnabled(info, true);
}
_tokenInfos[i] = info;
}
_ntokens = tokens.length;
}
/***************************************
* Methods to change a token info
***************************************/
/* return soft weight in 1e18 */
function _getSoftWeight(uint256 info) internal pure returns (uint256 w) {
return ((info >> 160) & ((U256_1 << 20) - 1)) * 1e12;
}
function _setSoftWeight(
uint256 info,
uint256 w
)
internal
pure
returns (uint256 newInfo)
{
require (w <= W_ONE, "soft weight must <= 1e18");
// Only maintain 1e6 resolution.
newInfo = info & ~(((U256_1 << 20) - 1) << 160);
newInfo = newInfo | ((w / 1e12) << 160);
}
function _getHardWeight(uint256 info) internal pure returns (uint256 w) {
return ((info >> 180) & ((U256_1 << 20) - 1)) * 1e12;
}
function _setHardWeight(
uint256 info,
uint256 w
)
internal
pure
returns (uint256 newInfo)
{
require (w <= W_ONE, "hard weight must <= 1e18");
// Only maintain 1e6 resolution.
newInfo = info & ~(((U256_1 << 20) - 1) << 180);
newInfo = newInfo | ((w / 1e12) << 180);
}
function _getDecimalMulitiplier(uint256 info) internal pure returns (uint256 dec) {
return (info >> (160 + DECM_OFF)) & ((U256_1 << 5) - 1);
}
function _setDecimalMultiplier(
uint256 info,
uint256 decm
)
internal
pure
returns (uint256 newInfo)
{
require (decm < 18, "decimal multipler is too large");
newInfo = info & ~(((U256_1 << 5) - 1) << (160 + DECM_OFF));
newInfo = newInfo | (decm << (160 + DECM_OFF));
}
function _isYEnabled(uint256 info) internal pure returns (bool) {
return (info >> (160 + YENABLE_OFF)) & 0x1 == 0x1;
}
function _setYEnabled(uint256 info, bool enabled) internal pure returns (uint256) {
if (enabled) {
return info | (U256_1 << (160 + YENABLE_OFF));
} else {
return info & ~(U256_1 << (160 + YENABLE_OFF));
}
}
function _setTID(uint256 info, uint256 tid) internal pure returns (uint256) {
require (tid < 256, "tid is too large");
require (_getTID(info) == 0, "tid cannot set again");
return info | (tid << (160 + TID_OFF));
}
function _getTID(uint256 info) internal pure returns (uint256) {
return (info >> (160 + TID_OFF)) & 0xFF;
}
/****************************************
* Owner methods
****************************************/
function pause(uint256 flag) external onlyOwner {
_pause(flag);
}
function unpause(uint256 flag) external onlyOwner {
_unpause(flag);
}
function changeRewardCollector(address newCollector) external onlyOwner {
_rewardCollector = newCollector;
}
function adjustWeights(
uint8 tid,
uint256 newSoftWeight,
uint256 newHardWeight
)
external
onlyOwner
{
require(newSoftWeight <= newHardWeight, "Soft-limit weight must <= Hard-limit weight");
require(newHardWeight <= W_ONE, "hard-limit weight must <= 1");
require(tid < _ntokens, "Backed token not exists");
_tokenInfos[tid] = _setSoftWeight(_tokenInfos[tid], newSoftWeight);
_tokenInfos[tid] = _setHardWeight(_tokenInfos[tid], newHardWeight);
}
function changeSwapFee(uint256 swapFee) external onlyOwner {
require(swapFee <= SWAP_FEE_MAX, "Swap fee must is too large");
_swapFee = swapFee;
}
function changeRedeemFee(
uint256 redeemFee
)
external
onlyOwner
{
require(redeemFee <= REDEEM_FEE_MAX, "Redeem fee is too large");
_redeemFee = redeemFee;
}
function changeAdminFeePct(uint256 pct) external onlyOwner {
require (pct <= ADMIN_FEE_PCT_MAX, "Admin fee pct is too large");
_adminFeePct = pct;
}
function changeAdminInterestPct(uint256 pct) external onlyOwner {
require (pct <= ADMIN_FEE_PCT_MAX, "Admin interest fee pct is too large");
_adminInterestPct = pct;
}
function initialize(
uint8 tid,
uint256 bTokenAmount
)
external
onlyOwner
{
require(tid < _ntokens, "Backed token not exists");
uint256 info = _tokenInfos[tid];
address addr = address(info);
IERC20(addr).safeTransferFrom(
msg.sender,
address(this),
bTokenAmount
);
_totalBalance = _totalBalance.add(bTokenAmount.mul(_normalizeBalance(info)));
_mint(msg.sender, bTokenAmount.mul(_normalizeBalance(info)));
}
function addToken(
address addr,
address yAddr,
uint256 softWeight,
uint256 hardWeight,
uint256 decMultiplier
)
external
onlyOwner
{
uint256 tid = _ntokens;
for (uint256 i = 0; i < tid; i++) {
require(address(_tokenInfos[i]) != addr, "cannot add dup token");
}
require (softWeight <= hardWeight, "soft weight must <= hard weight");
uint256 info = uint256(addr);
info = _setTID(info, tid);
info = _setYEnabled(info, yAddr != address(0x0));
info = _setSoftWeight(info, softWeight);
info = _setHardWeight(info, hardWeight);
info = _setDecimalMultiplier(info, decMultiplier);
_tokenInfos[tid] = info;
_yTokenAddresses[tid] = yAddr;
// _balances[tid] = 0; // no need to set
_ntokens = tid.add(1);
}
function setYEnabled(uint256 tid, address yAddr) external onlyOwner {
uint256 info = _tokenInfos[tid];
if (_yTokenAddresses[tid] != address(0x0)) {
// Withdraw all tokens from yToken, and clear yBalance.
uint256 pricePerShare = YERC20(_yTokenAddresses[tid]).getPricePerFullShare();
uint256 share = YERC20(_yTokenAddresses[tid]).balanceOf(address(this));
uint256 cash = _getCashBalance(info);
YERC20(_yTokenAddresses[tid]).withdraw(share);
uint256 dcash = _getCashBalance(info).sub(cash);
require(dcash >= pricePerShare.mul(share).div(W_ONE), "ytoken withdraw amount < expected");
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(tid, dcash);
_yBalances[tid] = 0;
}
info = _setYEnabled(info, yAddr != address(0x0));
_yTokenAddresses[tid] = yAddr;
_tokenInfos[tid] = info;
// If yAddr != 0x0, we will rebalance in next swap/mint/redeem/rebalance call.
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
* See LICENSE_LOG.md for license.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function lg2(int128 x) internal pure returns (int128) {
require (x > 0, "x must be positive");
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {xc >>= 64; msb += 64;}
if (xc >= 0x100000000) {xc >>= 32; msb += 32;}
if (xc >= 0x10000) {xc >>= 16; msb += 16;}
if (xc >= 0x100) {xc >>= 8; msb += 8;}
if (xc >= 0x10) {xc >>= 4; msb += 4;}
if (xc >= 0x4) {xc >>= 2; msb += 2;}
if (xc >= 0x2) {msb += 1;} // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256 (x) << (127 - msb);
/* 20 iterations so that the resolution is aboout 2^-20 \approx 5e-6 */
for (int256 bit = 0x8000000000000000; bit > 0x80000000000; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
function _safeToInt128(uint256 x) internal pure returns (int128 y) {
y = int128(x);
require(x == uint256(y), "Conversion to int128 failed");
return y;
}
/**
* @dev Return the approx logarithm of a value with log(x) where x <= 1.1.
* All values are in integers with (1e18 == 1.0).
*
* Requirements:
*
* - input value x must be greater than 1e18
*/
function _logApprox(uint256 x) internal pure returns (uint256 y) {
uint256 one = W_ONE;
require(x >= one, "logApprox: x must >= 1");
uint256 z = x - one;
uint256 zz = z.mul(z).div(one);
uint256 zzz = zz.mul(z).div(one);
uint256 zzzz = zzz.mul(z).div(one);
uint256 zzzzz = zzzz.mul(z).div(one);
return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5));
}
/**
* @dev Return the logarithm of a value.
* All values are in integers with (1e18 == 1.0).
*
* Requirements:
*
* - input value x must be greater than 1e18
*/
function _log(uint256 x) internal pure returns (uint256 y) {
require(x >= W_ONE, "log(x): x must be greater than 1");
require(x < (W_ONE << 63), "log(x): x is too large");
if (x <= W_ONE.add(W_ONE.div(10))) {
return _logApprox(x);
}
/* Convert to 64.64 float point */
int128 xx = _safeToInt128((x << 64) / W_ONE);
int128 yy = lg2(xx);
/* log(2) * 1e18 \approx 693147180559945344 */
y = (uint256(yy) * 693147180559945344) >> 64;
return y;
}
/**
* Return weights and cached balances of all tokens
* Note that the cached balance does not include the accrued interest since last rebalance.
*/
function _getBalancesAndWeights()
internal
view
returns (uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance)
{
uint256 ntokens = _ntokens;
balances = new uint256[](ntokens);
softWeights = new uint256[](ntokens);
hardWeights = new uint256[](ntokens);
totalBalance = 0;
for (uint8 i = 0; i < ntokens; i++) {
uint256 info = _tokenInfos[i];
balances[i] = _getCashBalance(info);
if (_isYEnabled(info)) {
balances[i] = balances[i].add(_yBalances[i]);
}
totalBalance = totalBalance.add(balances[i]);
softWeights[i] = _getSoftWeight(info);
hardWeights[i] = _getHardWeight(info);
}
}
function _getBalancesAndInfos()
internal
view
returns (uint256[] memory balances, uint256[] memory infos, uint256 totalBalance)
{
uint256 ntokens = _ntokens;
balances = new uint256[](ntokens);
infos = new uint256[](ntokens);
totalBalance = 0;
for (uint8 i = 0; i < ntokens; i++) {
infos[i] = _tokenInfos[i];
balances[i] = _getCashBalance(infos[i]);
if (_isYEnabled(infos[i])) {
balances[i] = balances[i].add(_yBalances[i]);
}
totalBalance = totalBalance.add(balances[i]);
}
}
function _getBalance(uint256 info) internal view returns (uint256 balance) {
balance = _getCashBalance(info);
if (_isYEnabled(info)) {
balance = balance.add(_yBalances[_getTID(info)]);
}
}
function getBalance(uint256 tid) public view returns (uint256) {
return _getBalance(_tokenInfos[tid]);
}
function _normalizeBalance(uint256 info) internal pure returns (uint256) {
uint256 decm = _getDecimalMulitiplier(info);
return 10 ** decm;
}
/* @dev Return normalized cash balance of a token */
function _getCashBalance(uint256 info) internal view returns (uint256) {
return IERC20(address(info)).balanceOf(address(this))
.mul(_normalizeBalance(info));
}
function _getBalanceDetail(
uint256 info
)
internal
view
returns (uint256 pricePerShare, uint256 cashUnnormalized, uint256 yBalanceUnnormalized)
{
address yAddr = _yTokenAddresses[_getTID(info)];
pricePerShare = YERC20(yAddr).getPricePerFullShare();
cashUnnormalized = IERC20(address(info)).balanceOf(address(this));
uint256 share = YERC20(yAddr).balanceOf(address(this));
yBalanceUnnormalized = share.mul(pricePerShare).div(W_ONE);
}
/**************************************************************************************
* Methods for rebalance cash reserve
* After rebalancing, we will have cash reserve equaling to 10% of total balance
* There are two conditions to trigger a rebalancing
* - if there is insufficient cash for withdraw; or
* - if the cash reserve is greater than 20% of total balance.
* Note that we use a cached version of total balance to avoid high gas cost on calling
* getPricePerFullShare().
*************************************************************************************/
function _updateTotalBalanceWithNewYBalance(
uint256 tid,
uint256 yBalanceNormalizedNew
)
internal
{
uint256 adminFee = 0;
uint256 yBalanceNormalizedOld = _yBalances[tid];
// They yBalance should not be decreasing, but just in case,
if (yBalanceNormalizedNew >= yBalanceNormalizedOld) {
adminFee = (yBalanceNormalizedNew - yBalanceNormalizedOld).mul(_adminInterestPct).div(W_ONE);
}
_totalBalance = _totalBalance
.sub(yBalanceNormalizedOld)
.add(yBalanceNormalizedNew)
.sub(adminFee);
}
function _rebalanceReserve(
uint256 info
)
internal
{
require(_isYEnabled(info), "yToken must be enabled for rebalancing");
uint256 pricePerShare;
uint256 cashUnnormalized;
uint256 yBalanceUnnormalized;
(pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);
uint256 tid = _getTID(info);
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(tid, yBalanceUnnormalized.mul(_normalizeBalance(info)));
uint256 targetCash = yBalanceUnnormalized.add(cashUnnormalized).div(10);
if (cashUnnormalized > targetCash) {
uint256 depositAmount = cashUnnormalized.sub(targetCash);
// Reset allowance to bypass possible allowance check (e.g., USDT)
IERC20(address(info)).safeApprove(_yTokenAddresses[tid], 0);
IERC20(address(info)).safeApprove(_yTokenAddresses[tid], depositAmount);
// Calculate acutal deposit in the case that some yTokens may return partial deposit.
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
YERC20(_yTokenAddresses[tid]).deposit(depositAmount);
uint256 actualDeposit = balanceBefore.sub(IERC20(address(info)).balanceOf(address(this)));
_yBalances[tid] = yBalanceUnnormalized.add(actualDeposit).mul(_normalizeBalance(info));
} else {
uint256 expectedWithdraw = targetCash.sub(cashUnnormalized);
if (expectedWithdraw == 0) {
return;
}
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
// Withdraw +1 wei share to make sure actual withdraw >= expected.
YERC20(_yTokenAddresses[tid]).withdraw(expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1));
uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);
require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken");
_yBalances[tid] = yBalanceUnnormalized.sub(actualWithdraw).mul(_normalizeBalance(info));
}
}
/* @dev Forcibly rebalance so that cash reserve is about 10% of total. */
function rebalanceReserve(
uint256 tid
)
external
nonReentrantAndUnpausedV1
{
_rebalanceReserve(_tokenInfos[tid]);
}
/*
* @dev Rebalance the cash reserve so that
* cash reserve consists of 10% of total balance after substracting amountUnnormalized.
*
* Assume that current cash reserve < amountUnnormalized.
*/
function _rebalanceReserveSubstract(
uint256 info,
uint256 amountUnnormalized
)
internal
{
require(_isYEnabled(info), "yToken must be enabled for rebalancing");
uint256 pricePerShare;
uint256 cashUnnormalized;
uint256 yBalanceUnnormalized;
(pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(
_getTID(info),
yBalanceUnnormalized.mul(_normalizeBalance(info))
);
// Evaluate the shares to withdraw so that cash = 10% of total
uint256 expectedWithdraw = cashUnnormalized.add(yBalanceUnnormalized).sub(
amountUnnormalized).div(10).add(amountUnnormalized).sub(cashUnnormalized);
if (expectedWithdraw == 0) {
return;
}
// Withdraw +1 wei share to make sure actual withdraw >= expected.
uint256 withdrawShares = expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1);
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
YERC20(_yTokenAddresses[_getTID(info)]).withdraw(withdrawShares);
uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);
require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken");
_yBalances[_getTID(info)] = yBalanceUnnormalized.sub(actualWithdraw)
.mul(_normalizeBalance(info));
}
/* @dev Transfer the amount of token out. Rebalance the cash reserve if needed */
function _transferOut(
uint256 info,
uint256 amountUnnormalized,
uint256 adminFee
)
internal
{
uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));
if (_isYEnabled(info)) {
if (IERC20(address(info)).balanceOf(address(this)) < amountUnnormalized) {
_rebalanceReserveSubstract(info, amountUnnormalized);
}
}
IERC20(address(info)).safeTransfer(
msg.sender,
amountUnnormalized
);
_totalBalance = _totalBalance
.sub(amountNormalized)
.sub(adminFee.mul(_normalizeBalance(info)));
}
/* @dev Transfer the amount of token in. Rebalance the cash reserve if needed */
function _transferIn(
uint256 info,
uint256 amountUnnormalized
)
internal
{
uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));
IERC20(address(info)).safeTransferFrom(
msg.sender,
address(this),
amountUnnormalized
);
_totalBalance = _totalBalance.add(amountNormalized);
// If there is saving ytoken, save the balance in _balance.
if (_isYEnabled(info)) {
uint256 tid = _getTID(info);
/* Check rebalance if needed */
uint256 cash = _getCashBalance(info);
if (cash > cash.add(_yBalances[tid]).mul(2).div(10)) {
_rebalanceReserve(info);
}
}
}
/**************************************************************************************
* Methods for minting LP tokens
*************************************************************************************/
/*
* @dev Return the amount of sUSD should be minted after depositing bTokenAmount into the pool
* @param bTokenAmountNormalized - normalized amount of token to be deposited
* @param oldBalance - normalized amount of all tokens before the deposit
* @param oldTokenBlance - normalized amount of the balance of the token to be deposited in the pool
* @param softWeight - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeight - maximum percentage of the token
*/
function _getMintAmount(
uint256 bTokenAmountNormalized,
uint256 oldBalance,
uint256 oldTokenBalance,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256 s)
{
/* Evaluate new percentage */
uint256 newBalance = oldBalance.add(bTokenAmountNormalized);
uint256 newTokenBalance = oldTokenBalance.add(bTokenAmountNormalized);
/* If new percentage <= soft weight, no penalty */
if (newTokenBalance.mul(W_ONE) <= softWeight.mul(newBalance)) {
return bTokenAmountNormalized;
}
require (
newTokenBalance.mul(W_ONE) <= hardWeight.mul(newBalance),
"mint: new percentage exceeds hard weight"
);
s = 0;
/* if new percentage <= soft weight, get the beginning of integral with penalty. */
if (oldTokenBalance.mul(W_ONE) <= softWeight.mul(oldBalance)) {
s = oldBalance.mul(softWeight).sub(oldTokenBalance.mul(W_ONE)).div(W_ONE.sub(softWeight));
}
// bx + (tx - bx) * (w - 1) / (w - v) + (S - x) * ln((S + tx) / (S + bx)) / (w - v)
uint256 t;
{ // avoid stack too deep error
uint256 ldelta = _log(newBalance.mul(W_ONE).div(oldBalance.add(s)));
t = oldBalance.sub(oldTokenBalance).mul(ldelta);
}
t = t.sub(bTokenAmountNormalized.sub(s).mul(W_ONE.sub(hardWeight)));
t = t.div(hardWeight.sub(softWeight));
s = s.add(t);
require(s <= bTokenAmountNormalized, "penalty should be positive");
}
/*
* @dev Given the token id and the amount to be deposited, return the amount of lp token
*/
function getMintAmount(
uint256 bTokenIdx,
uint256 bTokenAmount
)
public
view
returns (uint256 lpTokenAmount)
{
require(bTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[bTokenIdx];
require(info != 0, "Backed token is not found!");
// Obtain normalized balances
uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
// Gas saving: Use cached totalBalance with accrued interest since last rebalance.
uint256 totalBalance = _totalBalance;
uint256 sTokenAmount = _getMintAmount(
bTokenAmountNormalized,
totalBalance,
_getBalance(info),
_getSoftWeight(info),
_getHardWeight(info)
);
return sTokenAmount.mul(totalSupply()).div(totalBalance);
}
/*
* @dev Given the token id and the amount to be deposited, mint lp token
*/
function mint(
uint256 bTokenIdx,
uint256 bTokenAmount,
uint256 lpTokenMintedMin
)
external
nonReentrantAndUnpausedV1
{
uint256 lpTokenAmount = getMintAmount(bTokenIdx, bTokenAmount);
require(
lpTokenAmount >= lpTokenMintedMin,
"lpToken minted should >= minimum lpToken asked"
);
_transferIn(_tokenInfos[bTokenIdx], bTokenAmount);
_mint(msg.sender, lpTokenAmount);
emit Mint(msg.sender, bTokenAmount, lpTokenAmount);
}
/**************************************************************************************
* Methods for redeeming LP tokens
*************************************************************************************/
/*
* @dev Return number of sUSD that is needed to redeem corresponding amount of token for another
* token
* Withdrawing a token will result in increased percentage of other tokens, where
* the function is used to calculate the penalty incured by the increase of one token.
* @param totalBalance - normalized amount of the sum of all tokens
* @param tokenBlance - normalized amount of the balance of a non-withdrawn token
* @param redeemAount - normalized amount of the token to be withdrawn
* @param softWeight - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeight - maximum percentage of the token
*/
function _redeemPenaltyFor(
uint256 totalBalance,
uint256 tokenBalance,
uint256 redeemAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
/* Soft weight is satisfied. No penalty is incurred */
if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
return 0;
}
require (
tokenBalance.mul(W_ONE) <= newTotalBalance.mul(hardWeight),
"redeem: hard-limit weight is broken"
);
uint256 bx = 0;
// Evaluate the beginning of the integral for broken soft weight
if (tokenBalance.mul(W_ONE) < totalBalance.mul(softWeight)) {
bx = totalBalance.sub(tokenBalance.mul(W_ONE).div(softWeight));
}
// x * (w - v) / w / w * ln(1 + (tx - bx) * w / (w * (S - tx) - x)) - (tx - bx) * v / w
uint256 tdelta = tokenBalance.mul(
_log(W_ONE.add(redeemAmount.sub(bx).mul(hardWeight).div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))));
uint256 s1 = tdelta.mul(hardWeight.sub(softWeight))
.div(hardWeight).div(hardWeight);
uint256 s2 = redeemAmount.sub(bx).mul(softWeight).div(hardWeight);
return s1.sub(s2);
}
/*
* @dev Return number of sUSD that is needed to redeem corresponding amount of token
* Withdrawing a token will result in increased percentage of other tokens, where
* the function is used to calculate the penalty incured by the increase.
* @param bTokenIdx - token id to be withdrawn
* @param totalBalance - normalized amount of the sum of all tokens
* @param balances - normalized amount of the balance of each token
* @param softWeights - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeights - maximum percentage of the token
* @param redeemAount - normalized amount of the token to be withdrawn
*/
function _redeemPenaltyForAll(
uint256 bTokenIdx,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 redeemAmount
)
internal
pure
returns (uint256)
{
uint256 s = 0;
for (uint256 k = 0; k < balances.length; k++) {
if (k == bTokenIdx) {
continue;
}
s = s.add(
_redeemPenaltyFor(totalBalance, balances[k], redeemAmount, softWeights[k], hardWeights[k]));
}
return s;
}
/*
* @dev Calculate the derivative of the penalty function.
* Same parameters as _redeemPenaltyFor.
*/
function _redeemPenaltyDerivativeForOne(
uint256 totalBalance,
uint256 tokenBalance,
uint256 redeemAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 dfx = W_ONE;
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
/* Soft weight is satisfied. No penalty is incurred */
if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
return dfx;
}
// dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w
return dfx.add(tokenBalance.mul(hardWeight.sub(softWeight))
.div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))
.sub(softWeight.mul(W_ONE).div(hardWeight));
}
/*
* @dev Calculate the derivative of the penalty function.
* Same parameters as _redeemPenaltyForAll.
*/
function _redeemPenaltyDerivativeForAll(
uint256 bTokenIdx,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 redeemAmount
)
internal
pure
returns (uint256)
{
uint256 dfx = W_ONE;
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
for (uint256 k = 0; k < balances.length; k++) {
if (k == bTokenIdx) {
continue;
}
/* Soft weight is satisfied. No penalty is incurred */
uint256 softWeight = softWeights[k];
uint256 balance = balances[k];
if (balance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
continue;
}
// dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w
uint256 hardWeight = hardWeights[k];
dfx = dfx.add(balance.mul(hardWeight.sub(softWeight))
.div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(balance)))
.sub(softWeight.mul(W_ONE).div(hardWeight));
}
return dfx;
}
/*
* @dev Given the amount of sUSD to be redeemed, find the max token can be withdrawn
* This function is for swap only.
* @param tidOutBalance - the balance of the token to be withdrawn
* @param totalBalance - total balance of all tokens
* @param tidInBalance - the balance of the token to be deposited
* @param sTokenAmount - the amount of sUSD to be redeemed
* @param softWeight/hardWeight - normalized weights for the token to be withdrawn.
*/
function _redeemFindOne(
uint256 tidOutBalance,
uint256 totalBalance,
uint256 tidInBalance,
uint256 sTokenAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 redeemAmountNormalized = Math.min(
sTokenAmount,
tidOutBalance.mul(999).div(1000)
);
for (uint256 i = 0; i < 256; i++) {
uint256 sNeeded = redeemAmountNormalized.add(
_redeemPenaltyFor(
totalBalance,
tidInBalance,
redeemAmountNormalized,
softWeight,
hardWeight
));
uint256 fx = 0;
if (sNeeded > sTokenAmount) {
fx = sNeeded - sTokenAmount;
} else {
fx = sTokenAmount - sNeeded;
}
// penalty < 1e-5 of out amount
if (fx < redeemAmountNormalized / 100000) {
require(redeemAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
require(redeemAmountNormalized <= tidOutBalance, "Redeem error: insufficient balance");
return redeemAmountNormalized;
}
uint256 dfx = _redeemPenaltyDerivativeForOne(
totalBalance,
tidInBalance,
redeemAmountNormalized,
softWeight,
hardWeight
);
if (sNeeded > sTokenAmount) {
redeemAmountNormalized = redeemAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
} else {
redeemAmountNormalized = redeemAmountNormalized.add(fx.mul(W_ONE).div(dfx));
}
}
require (false, "cannot find proper resolution of fx");
}
/*
* @dev Given the amount of sUSD token to be redeemed, find the max token can be withdrawn
* @param bTokenIdx - the id of the token to be withdrawn
* @param sTokenAmount - the amount of sUSD token to be redeemed
* @param totalBalance - total balance of all tokens
* @param balances/softWeight/hardWeight - normalized balances/weights of all tokens
*/
function _redeemFind(
uint256 bTokenIdx,
uint256 sTokenAmount,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
internal
pure
returns (uint256)
{
uint256 bTokenAmountNormalized = Math.min(
sTokenAmount,
balances[bTokenIdx].mul(999).div(1000)
);
for (uint256 i = 0; i < 256; i++) {
uint256 sNeeded = bTokenAmountNormalized.add(
_redeemPenaltyForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
));
uint256 fx = 0;
if (sNeeded > sTokenAmount) {
fx = sNeeded - sTokenAmount;
} else {
fx = sTokenAmount - sNeeded;
}
// penalty < 1e-5 of out amount
if (fx < bTokenAmountNormalized / 100000) {
require(bTokenAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
require(bTokenAmountNormalized <= balances[bTokenIdx], "Redeem error: insufficient balance");
return bTokenAmountNormalized;
}
uint256 dfx = _redeemPenaltyDerivativeForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
);
if (sNeeded > sTokenAmount) {
bTokenAmountNormalized = bTokenAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
} else {
bTokenAmountNormalized = bTokenAmountNormalized.add(fx.mul(W_ONE).div(dfx));
}
}
require (false, "cannot find proper resolution of fx");
}
/*
* @dev Given token id and LP token amount, return the max amount of token can be withdrawn
* @param tid - the id of the token to be withdrawn
* @param lpTokenAmount - the amount of LP token
*/
function _getRedeemByLpTokenAmount(
uint256 tid,
uint256 lpTokenAmount
)
internal
view
returns (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee)
{
require(lpTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[tid];
require(info != 0, "Backed token is not found!");
// Obtain normalized balances.
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
uint256[] memory balances;
uint256[] memory softWeights;
uint256[] memory hardWeights;
(balances, softWeights, hardWeights, totalBalance) = _getBalancesAndWeights();
bTokenAmount = _redeemFind(
tid,
lpTokenAmount.mul(totalBalance).div(totalSupply()),
totalBalance,
balances,
softWeights,
hardWeights
).div(_normalizeBalance(info));
uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
adminFee = fee.mul(_adminFeePct).div(W_ONE);
bTokenAmount = bTokenAmount.sub(fee);
}
function getRedeemByLpTokenAmount(
uint256 tid,
uint256 lpTokenAmount
)
public
view
returns (uint256 bTokenAmount)
{
(bTokenAmount,,) = _getRedeemByLpTokenAmount(tid, lpTokenAmount);
}
function redeemByLpToken(
uint256 bTokenIdx,
uint256 lpTokenAmount,
uint256 bTokenMin
)
external
nonReentrantAndUnpausedV1
{
(uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee) = _getRedeemByLpTokenAmount(
bTokenIdx,
lpTokenAmount
);
require(bTokenAmount >= bTokenMin, "bToken returned < min bToken asked");
// Make sure _totalBalance == sum(balances)
_collectReward(totalBalance);
_burn(msg.sender, lpTokenAmount);
_transferOut(_tokenInfos[bTokenIdx], bTokenAmount, adminFee);
emit Redeem(msg.sender, bTokenAmount, lpTokenAmount);
}
/* @dev Redeem a specific token from the pool.
* Fee will be incured. Will incur penalty if the pool is unbalanced.
*/
function redeem(
uint256 bTokenIdx,
uint256 bTokenAmount,
uint256 lpTokenBurnedMax
)
external
nonReentrantAndUnpausedV1
{
require(bTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[bTokenIdx];
require (info != 0, "Backed token is not found!");
// Obtain normalized balances.
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
(
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 totalBalance
) = _getBalancesAndWeights();
uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
require(balances[bTokenIdx] >= bTokenAmountNormalized, "Insufficient token to redeem");
_collectReward(totalBalance);
uint256 lpAmount = bTokenAmountNormalized.add(
_redeemPenaltyForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
)).mul(totalSupply()).div(totalBalance);
require(lpAmount <= lpTokenBurnedMax, "burned token should <= maximum lpToken offered");
_burn(msg.sender, lpAmount);
/* Transfer out the token after deducting the fee. Rebalance cash reserve if needed */
uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
_transferOut(
_tokenInfos[bTokenIdx],
bTokenAmount.sub(fee),
fee.mul(_adminFeePct).div(W_ONE)
);
emit Redeem(msg.sender, bTokenAmount, lpAmount);
}
/**************************************************************************************
* Methods for swapping tokens
*************************************************************************************/
/*
* @dev Return the maximum amount of token can be withdrawn after depositing another token.
* @param bTokenIdIn - the id of the token to be deposited
* @param bTokenIdOut - the id of the token to be withdrawn
* @param bTokenInAmount - the amount (unnormalized) of the token to be deposited
*/
function getSwapAmount(
uint256 bTokenIdxIn,
uint256 bTokenIdxOut,
uint256 bTokenInAmount
)
external
view
returns (uint256 bTokenOutAmount)
{
uint256 infoIn = _tokenInfos[bTokenIdxIn];
uint256 infoOut = _tokenInfos[bTokenIdxOut];
(bTokenOutAmount,) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);
}
function _getSwapAmount(
uint256 infoIn,
uint256 infoOut,
uint256 bTokenInAmount
)
internal
view
returns (uint256 bTokenOutAmount, uint256 adminFee)
{
require(bTokenInAmount > 0, "Amount must be greater than 0");
require(infoIn != 0, "Backed token is not found!");
require(infoOut != 0, "Backed token is not found!");
require (infoIn != infoOut, "Tokens for swap must be different!");
// Gas saving: Use cached totalBalance without accrued interest since last rebalance.
// Here we assume that the interest earned from the underlying platform is too small to
// impact the result significantly.
uint256 totalBalance = _totalBalance;
uint256 tidInBalance = _getBalance(infoIn);
uint256 sMinted = 0;
uint256 softWeight = _getSoftWeight(infoIn);
uint256 hardWeight = _getHardWeight(infoIn);
{ // avoid stack too deep error
uint256 bTokenInAmountNormalized = bTokenInAmount.mul(_normalizeBalance(infoIn));
sMinted = _getMintAmount(
bTokenInAmountNormalized,
totalBalance,
tidInBalance,
softWeight,
hardWeight
);
totalBalance = totalBalance.add(bTokenInAmountNormalized);
tidInBalance = tidInBalance.add(bTokenInAmountNormalized);
}
uint256 tidOutBalance = _getBalance(infoOut);
// Find the bTokenOutAmount, only account for penalty from bTokenIdxIn
// because other tokens should not have penalty since
// bTokenOutAmount <= sMinted <= bTokenInAmount (normalized), and thus
// for other tokens, the percentage decreased by bTokenInAmount will be
// >= the percetnage increased by bTokenOutAmount.
bTokenOutAmount = _redeemFindOne(
tidOutBalance,
totalBalance,
tidInBalance,
sMinted,
softWeight,
hardWeight
).div(_normalizeBalance(infoOut));
uint256 fee = bTokenOutAmount.mul(_swapFee).div(W_ONE);
adminFee = fee.mul(_adminFeePct).div(W_ONE);
bTokenOutAmount = bTokenOutAmount.sub(fee);
}
/*
* @dev Swap a token to another.
* @param bTokenIdIn - the id of the token to be deposited
* @param bTokenIdOut - the id of the token to be withdrawn
* @param bTokenInAmount - the amount (unnormalized) of the token to be deposited
* @param bTokenOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn
*/
function swap(
uint256 bTokenIdxIn,
uint256 bTokenIdxOut,
uint256 bTokenInAmount,
uint256 bTokenOutMin
)
external
nonReentrantAndUnpausedV1
{
uint256 infoIn = _tokenInfos[bTokenIdxIn];
uint256 infoOut = _tokenInfos[bTokenIdxOut];
(
uint256 bTokenOutAmount,
uint256 adminFee
) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);
require(bTokenOutAmount >= bTokenOutMin, "Returned bTokenAmount < asked");
_transferIn(infoIn, bTokenInAmount);
_transferOut(infoOut, bTokenOutAmount, adminFee);
emit Swap(
msg.sender,
bTokenIdxIn,
bTokenIdxOut,
bTokenInAmount,
bTokenOutAmount
);
}
/*
* @dev Swap tokens given all token amounts
* The amounts are pre-fee amounts, and the user will provide max fee expected.
* Currently, do not support penalty.
* @param inOutFlag - 0 means deposit, and 1 means withdraw with highest bit indicating mint/burn lp token
* @param lpTokenMintedMinOrBurnedMax - amount of lp token to be minted/burnt
* @param maxFee - maximum percentage of fee will be collected for withdrawal
* @param amounts - list of unnormalized amounts of each token
*/
function swapAll(
uint256 inOutFlag,
uint256 lpTokenMintedMinOrBurnedMax,
uint256 maxFee,
uint256[] calldata amounts
)
external
nonReentrantAndUnpausedV1
{
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
(
uint256[] memory balances,
uint256[] memory infos,
uint256 oldTotalBalance
) = _getBalancesAndInfos();
// Make sure _totalBalance = oldTotalBalance = sum(_getBalance()'s)
_collectReward(oldTotalBalance);
require (amounts.length == balances.length, "swapAll amounts length != ntokens");
uint256 newTotalBalance = 0;
uint256 depositAmount = 0;
{ // avoid stack too deep error
uint256[] memory newBalances = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
uint256 normalizedAmount = _normalizeBalance(infos[i]).mul(amounts[i]);
if (((inOutFlag >> i) & 1) == 0) {
// In
depositAmount = depositAmount.add(normalizedAmount);
newBalances[i] = balances[i].add(normalizedAmount);
} else {
// Out
newBalances[i] = balances[i].sub(normalizedAmount);
}
newTotalBalance = newTotalBalance.add(newBalances[i]);
}
for (uint256 i = 0; i < balances.length; i++) {
// If there is no mint/redeem, and the new total balance >= old one,
// then the weight must be non-increasing and thus there is no penalty.
if (amounts[i] == 0 && newTotalBalance >= oldTotalBalance) {
continue;
}
/*
* Accept the new amount if the following is satisfied
* np_i <= max(p_i, w_i)
*/
if (newBalances[i].mul(W_ONE) <= newTotalBalance.mul(_getSoftWeight(infos[i]))) {
continue;
}
// If no tokens in the pool, only weight contraints will be applied.
require(
oldTotalBalance != 0 &&
newBalances[i].mul(oldTotalBalance) <= newTotalBalance.mul(balances[i]),
"penalty is not supported in swapAll now"
);
}
}
// Calculate fee rate and mint/burn LP tokens
uint256 feeRate = 0;
uint256 lpMintedOrBurned = 0;
if (newTotalBalance == oldTotalBalance) {
// Swap only. No need to burn or mint.
lpMintedOrBurned = 0;
feeRate = _swapFee;
} else if (((inOutFlag >> 255) & 1) == 0) {
require (newTotalBalance >= oldTotalBalance, "swapAll mint: new total balance must >= old total balance");
lpMintedOrBurned = newTotalBalance.sub(oldTotalBalance).mul(totalSupply()).div(oldTotalBalance);
require(lpMintedOrBurned >= lpTokenMintedMinOrBurnedMax, "LP tokend minted < asked");
feeRate = _swapFee;
_mint(msg.sender, lpMintedOrBurned);
} else {
require (newTotalBalance <= oldTotalBalance, "swapAll redeem: new total balance must <= old total balance");
lpMintedOrBurned = oldTotalBalance.sub(newTotalBalance).mul(totalSupply()).div(oldTotalBalance);
require(lpMintedOrBurned <= lpTokenMintedMinOrBurnedMax, "LP tokend burned > offered");
uint256 withdrawAmount = oldTotalBalance - newTotalBalance;
/*
* The fee is determined by swapAmount * swap_fee + withdrawAmount * withdraw_fee,
* where swapAmount = depositAmount if withdrawAmount >= 0.
*/
feeRate = _swapFee.mul(depositAmount).add(_redeemFee.mul(withdrawAmount)).div(depositAmount + withdrawAmount);
_burn(msg.sender, lpMintedOrBurned);
}
emit SwapAll(msg.sender, amounts, inOutFlag, lpMintedOrBurned);
require (feeRate <= maxFee, "swapAll fee is greater than max fee user offered");
for (uint256 i = 0; i < balances.length; i++) {
if (amounts[i] == 0) {
continue;
}
if (((inOutFlag >> i) & 1) == 0) {
// In
_transferIn(infos[i], amounts[i]);
} else {
// Out (with fee)
uint256 fee = amounts[i].mul(feeRate).div(W_ONE);
uint256 adminFee = fee.mul(_adminFeePct).div(W_ONE);
_transferOut(infos[i], amounts[i].sub(fee), adminFee);
}
}
}
/**************************************************************************************
* Methods for others
*************************************************************************************/
/* @dev Collect admin fee so that _totalBalance == sum(_getBalances()'s) */
function _collectReward(uint256 totalBalance) internal {
uint256 oldTotalBalance = _totalBalance;
if (totalBalance != oldTotalBalance) {
if (totalBalance > oldTotalBalance) {
_mint(_rewardCollector, totalSupply().mul(totalBalance - oldTotalBalance).div(oldTotalBalance));
}
_totalBalance = totalBalance;
}
}
/* @dev Collect admin fee. Can be called by anyone */
function collectReward()
external
nonReentrantAndUnpausedV1
{
(,,,uint256 totalBalance) = _getBalancesAndWeights();
_collectReward(totalBalance);
}
function getTokenStats(uint256 bTokenIdx)
public
view
returns (uint256 softWeight, uint256 hardWeight, uint256 balance, uint256 decimals)
{
require(bTokenIdx < _ntokens, "Backed token is not found!");
uint256 info = _tokenInfos[bTokenIdx];
balance = _getBalance(info).div(_normalizeBalance(info));
softWeight = _getSoftWeight(info);
hardWeight = _getHardWeight(info);
decimals = ERC20(address(info)).decimals();
}
}
// File: contracts/Root.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract Root is UpgradeableExtension, SmoothyV1 {
constructor(
address[] memory tokens,
address[] memory yTokens,
uint256[] memory decMultipliers,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
public
UpgradeableExtension()
SmoothyV1(tokens, yTokens, decMultipliers, softWeights, hardWeights)
{ }
function upgradeTo(address newImplementation) external onlyOwner {
_upgradeTo(newImplementation);
}
} | return soft weight in 1e18 */ | function _getSoftWeight(uint256 info) internal pure returns (uint256 w) {
return ((info >> 160) & ((U256_1 << 20) - 1)) * 1e12;
}
| 523,957 | [
1,
2463,
8971,
3119,
316,
404,
73,
2643,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
588,
12468,
6544,
12,
11890,
5034,
1123,
13,
2713,
16618,
1135,
261,
11890,
5034,
341,
13,
288,
203,
3639,
327,
14015,
1376,
1671,
25430,
13,
473,
14015,
57,
5034,
67,
21,
2296,
4200,
13,
300,
404,
3719,
380,
404,
73,
2138,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-06-10
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// Contract implementarion
contract AVOCADO is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) private _isWhitelist;
mapping (address => uint256) private _lockedTime;
mapping (address => uint256) private _antiBot;
uint256 _3days = 3 * 1 days;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'AVOCADO🥑';
string private _symbol = 'AVOCADO🥑';
uint8 private _decimals = 9;
uint256 public _taxFee = 2;
uint256 public _charityFee = 5;
uint256 public _burnFee = 3;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousCharityFee = _charityFee;
uint256 private _previousBurnFee = _burnFee;
address payable public _charityWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 10000000000e9;
// We will set a minimum amount of tokens to be swaped => 5M
uint256 private _numOfTokensToExchangeForCharity = 5 * 10**6 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable charityWalletAddress) public {
_charityWalletAddress = charityWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _charityFee == 0 && _burnFee == 0) return;
_previousTaxFee = _taxFee;
_previousCharityFee = _charityFee;
_previousBurnFee = _burnFee;
_taxFee = 0;
_charityFee = 0;
_burnFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_charityFee = _previousCharityFee;
_burnFee = _previousBurnFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != uniswapV2Pair && recipient != uniswapV2Pair){
uint256 timePassed1 = block.timestamp - _antiBot[sender]; //check if 5 minutes are passed
uint256 timePassed2 = block.timestamp - _antiBot[recipient];
require(timePassed1 > 300 && timePassed2 > 300,'You must wait 5 minutes between trades');
_antiBot[sender] = block.timestamp; _antiBot[recipient] = block.timestamp;
}
//If sender has purchased during presale, must wait 72h to transfer.
if(_isWhitelist[sender] == true) {
uint256 time_since_purchase = block.timestamp - _lockedTime[sender];
require(time_since_purchase > _3days, 'You must wait 72h from purchase');
_isWhitelist[sender] == false;
}
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap?
// also, don't get caught in a circular charity event.
// also, don't swap if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
// We need to swap the current tokens to ETH and send to the charity wallet
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
//transfer amount, it will take tax and charity fee
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendETHToCharity(uint256 amount) private {
_charityWalletAddress.transfer(amount);
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToCharity(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
uint256 burnAmt = amount.mul(_burnFee).div(100);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount.sub(burnAmt));
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount.sub(burnAmt));
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount.sub(burnAmt));
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount.sub(burnAmt));
} else {
_transferStandard(sender, recipient, amount.sub(burnAmt));
}
//remove fees to burn tokens
_taxFee = 0;
_charityFee = 0;
_transferStandard(sender, address(0), burnAmt);
_taxFee = _previousTaxFee;
_charityFee = _previousBurnFee;
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeCharity(tCharity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeCharity(uint256 tCharity) private {
uint256 currentRate = _getRate();
uint256 rCharity = tCharity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rCharity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tCharity);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tCharity) = _getTValues(tAmount, _taxFee, _charityFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tCharity);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 charityFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tCharity = tAmount.mul(charityFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tCharity);
return (tTransferAmount, tFee, tCharity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function _setCharityFee(uint256 charityFee) external onlyOwner() {
_charityFee = charityFee;
}
function _setCharityWallet(address payable charityWalletAddress) external onlyOwner() {
_charityWalletAddress = charityWalletAddress;
}
function distTokens (address[] memory recipients, uint256[] memory amounts) external onlyOwner(){
require(recipients.length == amounts.length, 'Arrays must have same size');
for(uint i = 0; i< recipients.length; i++){
_isWhitelist[recipients[i]] = true;
_lockedTime[recipients[i]] = block.timestamp;
uint256 amt = amounts[i].mul(10**9);
_tokenTransfer(msg.sender, recipients[i], amt, false);
}
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
} | If sender has purchased during presale, must wait 72h to transfer. We need to swap the current tokens to ETH and send to the charity walletif any account belongs to _isExcludedFromFee account then remove the fee | function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != uniswapV2Pair && recipient != uniswapV2Pair){
uint256 timePassed2 = block.timestamp - _antiBot[recipient];
require(timePassed1 > 300 && timePassed2 > 300,'You must wait 5 minutes between trades');
_antiBot[sender] = block.timestamp; _antiBot[recipient] = block.timestamp;
}
if(_isWhitelist[sender] == true) {
uint256 time_since_purchase = block.timestamp - _lockedTime[sender];
require(time_since_purchase > _3days, 'You must wait 72h from purchase');
_isWhitelist[sender] == false;
}
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForCharity;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToCharity(address(this).balance);
}
}
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
}
| 6,687,545 | [
1,
2047,
5793,
711,
5405,
343,
8905,
4982,
4075,
5349,
16,
1297,
2529,
19387,
76,
358,
7412,
18,
1660,
1608,
358,
7720,
326,
783,
2430,
358,
512,
2455,
471,
1366,
358,
326,
1149,
560,
9230,
430,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
445,
389,
13866,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3238,
288,
203,
5411,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
5411,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
2398,
203,
5411,
309,
12,
15330,
480,
640,
291,
91,
438,
58,
22,
4154,
597,
8027,
480,
640,
291,
91,
438,
58,
22,
4154,
15329,
203,
7734,
2254,
5034,
813,
22530,
22,
273,
1203,
18,
5508,
300,
389,
970,
77,
6522,
63,
20367,
15533,
203,
7734,
2583,
12,
957,
22530,
21,
405,
11631,
597,
813,
22530,
22,
405,
11631,
11189,
6225,
1297,
2529,
1381,
6824,
3086,
1284,
5489,
8284,
203,
7734,
389,
970,
77,
6522,
63,
15330,
65,
273,
1203,
18,
5508,
31,
389,
970,
77,
6522,
63,
20367,
65,
273,
1203,
18,
5508,
31,
203,
5411,
289,
203,
2398,
203,
5411,
309,
24899,
291,
18927,
63,
15330,
65,
422,
638,
13,
288,
203,
7734,
2254,
5034,
813,
67,
9256,
67,
12688,
12104,
273,
1203,
18,
5508,
300,
389,
15091,
950,
63,
15330,
15533,
203,
7734,
2583,
12,
957,
67,
9256,
67,
12688,
12104,
405,
389,
23,
9810,
16,
296,
6225,
1297,
2529,
19387,
76,
628,
23701,
8284,
203,
7734,
389,
291,
18927,
63,
15330,
65,
422,
629,
31,
203,
5411,
289,
203,
5411,
309,
12,
15330,
480,
3410,
1435,
597,
8027,
480,
3410,
10756,
203,
7734,
2583,
12,
8949,
1648,
389,
1896,
4188,
6275,
16,
315,
5912,
2
]
|
pragma solidity ^0.4.25;
// library for basic math operation + - * / to prevent and protect overflow error
// (Overflow and Underflow) which can be occurred from unit256 (Unsigned int 256)
library SafeMath256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if(a==0 || b==0)
return 0;
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b>0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require( b<= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
// Mandatory basic functions according to ERC20 standard
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
function totalSupply() public view returns (uint256);
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
}
// Contract Ownable is used to specified which person has right/permission to execute/invoke the specific function.
// Different from OnlyOwner which is the only owner of the smart contract who has right/permission to call
// the specific function. Aside from OnlyOwner,
// OnlyOwners can also be used which any of Owners can call the particular function.
contract Ownable {
// A list of owners which will be saved as a list here,
// and the values are the owner’s names.
// This to allow investors / NATEE Token buyers to trace/monitor
// who executes which functions written in this NATEE smart contract string [] ownerName;
string [] ownerName;
mapping (address=>bool) owners;
mapping (address=>uint256) ownerToProfile;
address owner;
// all events will be saved as log files
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event AddOwner(address newOwner,string name);
event RemoveOwner(address owner);
/**
* @dev Ownable constructor , initializes sender’s account and
* set as owner according to default value according to contract
*
*/
// this function will be executed during initial load and will keep the smart contract creator (msg.sender) as Owner
// and also saved in Owners. This smart contract creator/owner is
// Mr. Samret Wajanasathian CTO of Seitee Pte Ltd (https://seitee.com.sg , https://natee.io)
constructor() public {
owner = msg.sender;
owners[msg.sender] = true;
uint256 idx = ownerName.push("SAMRET WAJANASATHIAN");
ownerToProfile[msg.sender] = idx;
}
// function to check whether the given address is either Wallet address or Contract Address
function isContract(address _addr) internal view returns(bool){
uint256 length;
assembly{
length := extcodesize(_addr)
}
if(length > 0){
return true;
}
else {
return false;
}
}
// function to check if the executor is the owner? This to ensure that only the person
// who has right to execute/call the function has the permission to do so.
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
// This function has only one Owner. The ownership can be transferrable and only
// the current Owner will only be able to execute this function.
function transferOwnership(address newOwner,string newOwnerName) public onlyOwner{
require(isContract(newOwner) == false);
uint256 idx;
if(ownerToProfile[newOwner] == 0)
{
idx = ownerName.push(newOwnerName);
ownerToProfile[newOwner] = idx;
}
emit OwnershipTransferred(owner,newOwner);
owner = newOwner;
}
// Function to check if the person is listed in a group of Owners and determine
// if the person has the any permissions in this smart contract such as Exec permission.
modifier onlyOwners(){
require(owners[msg.sender] == true);
_;
}
// Function to add Owner into a list. The person who wanted to add a new owner into this list but be an existing
// member of the Owners list. The log will be saved and can be traced / monitor who’s called this function.
function addOwner(address newOwner,string newOwnerName) public onlyOwners{
require(owners[newOwner] == false);
require(newOwner != msg.sender);
if(ownerToProfile[newOwner] == 0)
{
uint256 idx = ownerName.push(newOwnerName);
ownerToProfile[newOwner] = idx;
}
owners[newOwner] = true;
emit AddOwner(newOwner,newOwnerName);
}
// Function to remove the Owner from the Owners list. The person who wanted to remove any owner from Owners
// List must be an existing member of the Owners List. The owner cannot evict himself from the Owners
// List by his own, this is to ensure that there is at least one Owner of this NATEE Smart Contract.
// This NATEE Smart Contract will become useless if there is no owner at all.
function removeOwner(address _owner) public onlyOwners{
require(_owner != msg.sender); // can't remove your self
owners[_owner] = false;
emit RemoveOwner(_owner);
}
// this function is to check of the given address is allowed to call/execute the particular function
// return true if the given address has right to execute the function.
// for transparency purpose, anyone can use this to trace/monitor the behaviors of this NATEE smart contract.
function isOwner(address _owner) public view returns(bool){
return owners[_owner];
}
// Function to check who’s executed the functions of smart contract. This returns the name of
// Owner and this give transparency of whose actions on this NATEE Smart Contract.
function getOwnerName(address ownerAddr) public view returns(string){
require(ownerToProfile[ownerAddr] > 0);
return ownerName[ownerToProfile[ownerAddr] - 1];
}
}
// ContractToken is for managing transactions of wallet address or contract address with its own
// criterias and conditions such as settlement.
contract ControlToken is Ownable{
mapping (address => bool) lockAddr;
address[] lockAddrList;
uint32 unlockDate;
bool disableBlock;
bool call2YLock;
mapping(address => bool) allowControl;
address[] exchangeAddress;
uint32 exchangeTimeOut;
event Call2YLock(address caller);
// Initially the lockin period is set for 100 years starting from the date of Smart Contract Deployment.
// The company will have to adjust it to 2 years for lockin period starting from the first day that
// NATEE token listed in exchange (in any exchange).
constructor() public{
unlockDate = uint32(now) + 36500 days; // Start Lock 100 Year first
}
// function to set Wallet Address that belong to Exclusive Exchange.
// The lockin period for this setting has its minimum of 6 months.
function setExchangeAddr(address _addr) onlyOwners public{
uint256 numEx = exchangeAddress.push(_addr);
if(numEx == 1){
exchangeTimeOut = uint32(now + 180 days);
}
}
// Function to adjust lockin period of Exclusive Exchange,
// this could unlock the lockin period and allow freedom trade.
function setExchangeTimeOut(uint32 timStemp) onlyOwners public{
exchangeTimeOut = timStemp;
}
// This function is used to set duration from 100 years to 2 years, start counting from the date that execute this function.
// To prevent early execution and to ensure that only the legitimate Owner can execute this function,
// Seitee Pte Ltd has logged all activities from this function which open for public for transparency.
// The generated log will be publicly published on ERC20 network, anyone can check/trace from the log
// that this function will never been called if there no confirmed Exchange that accepts NATEE Token.
// Any NATEE token holders who still serving lockin period, can ensure that there will be no repeatedly
// execution for this function (the repeatedly execution could lead to lockin period extension to more than 2 years).
// The constraint “call2YLock” is initialized as boolean “False” when the NATEE Smart Contract is created and will only
// be set to “true” when this function is executed. One the value changed from false > true, it will preserve the value forever.
function start2YearLock() onlyOwners public{
if(call2YLock == false){
unlockDate = uint32(now) + 730 days;
call2YLock = true;
emit Call2YLock(msg.sender);
}
}
function lockAddress(address _addr) internal{
if(lockAddr[_addr] == false)
{
lockAddr[_addr] = true;
lockAddrList.push(_addr);
}
}
function isLockAddr(address _addr) public view returns(bool){
return lockAddr[_addr];
}
// this internal function is used to add address into the locked address list.
function addLockAddress(address _addr) onlyOwners public{
if(lockAddr[_addr] == false)
{
lockAddr[_addr] = true;
lockAddrList.push(_addr);
}
}
// Function to unlock the token for all addresses. This function is open as public modifier
// stated to allow anyone to execute it. This to prevent the doubtful of delay of unlocking
// or any circumstances that prolong the unlocking. This just simply means, anyone can unlock
// the address for anyone in this Smart Contract.
function unlockAllAddress() public{
if(uint32(now) >= unlockDate)
{
for(uint256 i=0;i<lockAddrList.length;i++)
{
lockAddr[lockAddrList[i]] = false;
}
}
}
// The followings are the controls for Token Transfer, the Controls are managed by Seitee Pte Ltd
//========================= ADDRESS CONTROL =======================
// This internal function is to indicate that the Wallet Address has been allowed and let Seitee Pte Ltd
// to do transactions. The initial value is closed which means, Seitee Pte Lte cannot do any transactions.
function setAllowControl(address _addr) internal{
if(allowControl[_addr] == false)
allowControl[_addr] = true;
}
// this function is to check whether the given Wallet Address can be managed/controlled by Seitee Pte Ltd.
// If return “true” means, Seitee Pte Ltd take controls of this Wallet Address.
function checkAllowControl(address _addr) public view returns(bool){
return allowControl[_addr];
}
// NATEE Token system prevents the transfer of token to non-verified Wallet Address
// (the Wallet Address that hasn’t been verified thru KYC). This can also means that
// Token wont be transferable to other Wallet Address that not saved in this Smart Contract.
// This function is created for everyone to unlock the Wallet Address, once the Wallet Address is unlocked,
// the Wallet Address can’t be set to lock again. Our Smart Contract doesn’t have any line that
// contains “disableBlock = false”. The condition is when there is a new exchange in the system and
// fulfill the 6 months lockin period or less (depends on the value set).
function setDisableLock() public{
if(uint256(now) >= exchangeTimeOut && exchangeAddress.length > 0)
{
if(disableBlock == false)
disableBlock = true;
}
}
}
// NATEE token smart contract stored KYC Data on Blockchain for transparency.
// Only Seitee Pte Ltd has the access to this KYC data. The authorities/Government
// Agencies can be given the access to view this KYC data, too (subject to approval).
// Please note, this is not open publicly.
contract KYC is ControlToken{
struct KYCData{
bytes8 birthday; // yymmdd
bytes16 phoneNumber;
uint16 documentType; // 2 byte;
uint32 createTime; // 4 byte;
// --- 32 byte
bytes32 peronalID; // Passport หรือ idcard
// --- 32 byte
bytes32 name;
bytes32 surName;
bytes32 email;
bytes8 password;
}
KYCData[] internal kycDatas;
mapping (uint256=>address) kycDataForOwners;
mapping (address=>uint256) OwnerToKycData;
mapping (uint256=>address) internal kycSOSToOwner; //keccak256 for SOS function
event ChangePassword(address indexed owner_,uint256 kycIdx_);
event CreateKYCData(address indexed owner_, uint256 kycIdx_);
// Individual KYC data the parameter is index of the KYC data. Only Seitee Pte Ltd can view this data.
function getKYCData(uint256 _idx) onlyOwners view public returns(bytes16 phoneNumber_,
bytes8 birthday_,
uint16 documentType_,
bytes32 peronalID_,
bytes32 name_,
bytes32 surname_,
bytes32 email_){
require(_idx <= kycDatas.length && _idx > 0,"ERROR GetKYCData 01");
KYCData memory _kyc;
uint256 kycKey = _idx - 1;
_kyc = kycDatas[kycKey];
phoneNumber_ = _kyc.phoneNumber;
birthday_ = _kyc.birthday;
documentType_ = _kyc.documentType;
peronalID_ = _kyc.peronalID;
name_ = _kyc.name;
surname_ = _kyc.surName;
email_ = _kyc.email;
}
// function to view KYC data from registered Wallet Address. Only Seitee Pte Ltd has right to view this data.
function getKYCDataByAddr(address _addr) onlyOwners view public returns(bytes16 phoneNumber_,
bytes8 birthday_,
uint16 documentType_,
bytes32 peronalID_,
bytes32 name_,
bytes32 surname_,
bytes32 email_){
require(OwnerToKycData[_addr] > 0,"ERROR GetKYCData 02");
KYCData memory _kyc;
uint256 kycKey = OwnerToKycData[_addr] - 1;
_kyc = kycDatas[kycKey];
phoneNumber_ = _kyc.phoneNumber;
birthday_ = _kyc.birthday;
documentType_ = _kyc.documentType;
peronalID_ = _kyc.peronalID;
name_ = _kyc.name;
surname_ = _kyc.surName;
email_ = _kyc.email;
}
// The Owner can view the history records from KYC processes.
function getKYCData() view public returns(bytes16 phoneNumber_,
bytes8 birthday_,
uint16 documentType_,
bytes32 peronalID_,
bytes32 name_,
bytes32 surname_,
bytes32 email_){
require(OwnerToKycData[msg.sender] > 0,"ERROR GetKYCData 03"); // if == 0 not have data;
uint256 id = OwnerToKycData[msg.sender] - 1;
KYCData memory _kyc;
_kyc = kycDatas[id];
phoneNumber_ = _kyc.phoneNumber;
birthday_ = _kyc.birthday;
documentType_ = _kyc.documentType;
peronalID_ = _kyc.peronalID;
name_ = _kyc.name;
surname_ = _kyc.surName;
email_ = _kyc.email;
}
// 6 chars password which the Owner can update the password by himself/herself. Only the Owner can execute this function.
function changePassword(bytes8 oldPass_, bytes8 newPass_) public returns(bool){
require(OwnerToKycData[msg.sender] > 0,"ERROR changePassword");
uint256 id = OwnerToKycData[msg.sender] - 1;
if(kycDatas[id].password == oldPass_)
{
kycDatas[id].password = newPass_;
emit ChangePassword(msg.sender, id);
}
else
{
assert(kycDatas[id].password == oldPass_);
}
return true;
}
// function to create record of KYC data
function createKYCData(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password, bytes8 _birthday,bytes16 _phone,uint16 _docType,bytes32 _peronalID,address _wallet) onlyOwners public returns(uint256){
uint256 id = kycDatas.push(KYCData(_birthday, _phone, _docType, uint32(now) ,_peronalID, _name, _surname, _email, _password));
uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password)));
OwnerToKycData[_wallet] = id;
kycDataForOwners[id] = _wallet;
kycSOSToOwner[sosHash] = _wallet;
emit CreateKYCData(_wallet,id);
return id;
}
function maxKYCData() public view returns(uint256){
return kycDatas.length;
}
function haveKYCData(address _addr) public view returns(bool){
if(OwnerToKycData[_addr] > 0) return true;
else return false;
}
}
// Standard ERC20 function, no overriding at the moment.
contract StandarERC20 is ERC20{
using SafeMath256 for uint256;
mapping (address => uint256) balance;
mapping (address => mapping (address=>uint256)) allowed;
uint256 public totalSupply_;
address[] public holders;
mapping (address => uint256) holderToId;
event Transfer(address indexed from,address indexed to,uint256 value);
event Approval(address indexed owner,address indexed spender,uint256 value);
// Total number of Tokens
function totalSupply() public view returns (uint256){
return totalSupply_;
}
function balanceOf(address _walletAddress) public view returns (uint256){
return balance[_walletAddress];
}
// function to check on how many tokens set to be transfer between _owner and _spender. This is to check prior to confirm the transaction.
function allowance(address _owner, address _spender) public view returns (uint256){
return allowed[_owner][_spender];
}
// Standard function used to transfer the token according to ERC20 standard
function transfer(address _to, uint256 _value) public returns (bool){
require(_value <= balance[msg.sender]);
require(_to != address(0));
balance[msg.sender] = balance[msg.sender].sub(_value);
balance[_to] = balance[_to].add(_value);
emit Transfer(msg.sender,_to,_value);
return true;
}
// standard function to approve transfer of token
function approve(address _spender, uint256 _value)
public returns (bool){
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// standard function to request the money used after the sender has initialize the
// transition of money transfer. Only the beneficiary able to execute this function
// and the amount of money has been set as transferable by the sender.
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool){
require(_value <= balance[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balance[_from] = balance[_from].sub(_value);
balance[_to] = balance[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// additional function to store all NATEE Token holders as a list in blockchain.
// This could be use for bounty program in the future.
function addHolder(address _addr) internal{
if(holderToId[_addr] == 0)
{
uint256 idx = holders.push(_addr);
holderToId[_addr] = idx;
}
}
// function to request the top NATEE Token holders.
function getMaxHolders() external view returns(uint256){
return holders.length;
}
// function to read all indexes of NATEE Token holders.
function getHolder(uint256 idx) external view returns(address){
return holders[idx];
}
}
// Contract for co-founders and advisors which is total of 5,000,000 Tokens for co-founders
// and 4,000,000 tokens for advisors. Maximum NATEE token for advisor is 200,000 Tokens and
// the deficit from 4,000,000 tokens allocated to advisors, will be transferred to co-founders.
contract FounderAdvisor is StandarERC20,Ownable,KYC {
uint256 FOUNDER_SUPPLY = 5000000 ether;
uint256 ADVISOR_SUPPLY = 4000000 ether;
address[] advisors;
address[] founders;
mapping (address => uint256) advisorToID;
mapping (address => uint256) founderToID;
// will have true if already redeem.
// Advisor and founder can't be same people
bool public closeICO;
// Will have this value after close ICO
uint256 public TOKEN_PER_FOUNDER = 0 ether;
uint256 public TOKEN_PER_ADVISOR = 0 ether;
event AddFounder(address indexed newFounder,string nane,uint256 curFoounder);
event AddAdvisor(address indexed newAdvisor,string name,uint256 curAdvisor);
event CloseICO();
event RedeemAdvisor(address indexed addr_, uint256 value);
event RedeemFounder(address indexed addr_, uint256 value);
event ChangeAdvisorAddr(address indexed oldAddr_, address indexed newAddr_);
event ChangeFounderAddr(address indexed oldAddr_, address indexed newAddr_);
// function to add founders, name and surname will be logged. This
// function will be disabled after ICO closed.
function addFounder(address newAddr, string _name) onlyOwners external returns (bool){
require(closeICO == false);
require(founderToID[newAddr] == 0);
uint256 idx = founders.push(newAddr);
founderToID[newAddr] = idx;
emit AddFounder(newAddr, _name, idx);
return true;
}
// function to add advisors. This function will be disabled after ICO closed.
function addAdvisor(address newAdvis, string _name) onlyOwners external returns (bool){
require(closeICO == false);
require(advisorToID[newAdvis] == 0);
uint256 idx = advisors.push(newAdvis);
advisorToID[newAdvis] = idx;
emit AddAdvisor(newAdvis, _name, idx);
return true;
}
// function to update Advisor’s Wallet Address. If there is a need to remove the advisor,
// just input address = 0. This function will be disabled after ICO closed.
function changeAdvisorAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){
require(closeICO == false);
require(advisorToID[oldAddr] > 0); // it should be true if already have advisor
uint256 idx = advisorToID[oldAddr];
advisorToID[newAddr] = idx;
advisorToID[oldAddr] = 0;
advisors[idx - 1] = newAddr;
emit ChangeAdvisorAddr(oldAddr,newAddr);
return true;
}
// function to update founder’s Wallet Address. To remove the founder,
// pass the value of address = 0. This function will be disabled after ICO closed.
function changeFounderAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){
require(closeICO == false);
require(founderToID[oldAddr] > 0);
uint256 idx = founderToID[oldAddr];
founderToID[newAddr] = idx;
founderToID[oldAddr] = 0;
founders[idx - 1] = newAddr;
emit ChangeFounderAddr(oldAddr, newAddr);
return true;
}
function isAdvisor(address addr) public view returns(bool){
if(advisorToID[addr] > 0) return true;
else return false;
}
function isFounder(address addr) public view returns(bool){
if(founderToID[addr] > 0) return true;
else return false;
}
}
// Contract MyToken is created for extra permission to make a transfer of token. Typically,
// NATEE Token will be held and will only be able to transferred to those who has successfully
// done the KYC. For those who holds NATEE PRIVATE TOKEN at least 8,000,000 tokens is able to
// transfer the token to anyone with no limit.
contract MyToken is FounderAdvisor {
using SafeMath256 for uint256;
mapping(address => uint256) privateBalance;
event SOSTranfer(address indexed oldAddr_, address indexed newAddr_);
// standard function according to ERC20, modified by adding the condition of lockin period (2 years)
// for founders and advisors. Including the check whether the address has been KYC verified and is
// NATEE PRIVATE TOKEN holder will be able to freedomly trade the token.
function transfer(address _to, uint256 _value) public returns (bool){
if(lockAddr[msg.sender] == true) // 2 Year lock can Transfer only Lock Address
{
require(lockAddr[_to] == true);
}
// if total number of NATEE PRIVATE TOKEN is less than amount that wish to transfer
if(privateBalance[msg.sender] < _value){
if(disableBlock == false)
{
require(OwnerToKycData[msg.sender] > 0,"You Not have permission to Send");
require(OwnerToKycData[_to] > 0,"You not have permission to Recieve");
}
}
addHolder(_to);
if(super.transfer(_to, _value) == true)
{
// check if the total balance of token is less than transferred amount
if(privateBalance[msg.sender] <= _value)
{
privateBalance[_to] += privateBalance[msg.sender];
privateBalance[msg.sender] = 0;
}
else
{
privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value);
privateBalance[_to] = privateBalance[_to].add(_value);
}
return true;
}
return false;
}
// standard function ERC20, with additional criteria for 2 years lockin period for Founders and Advisors.
// Check if the owner of that Address has done the KYC successfully, if yes and having NATEE Private Token
// then, will be allowed to make the transfer.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool){
require(lockAddr[_from] == false); //2 Year Lock Can't Transfer
if(privateBalance[_from] < _value)
{
if(disableBlock == false)
{
require(OwnerToKycData[msg.sender] > 0, "You Not Have permission to Send");
require(OwnerToKycData[_to] > 0,"You not have permission to recieve");
}
}
addHolder(_to);
if(super.transferFrom(_from, _to, _value) == true)
{
if(privateBalance[msg.sender] <= _value)
{
privateBalance[_to] += privateBalance[msg.sender];
privateBalance[msg.sender] = 0;
}
else
{
privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value);
privateBalance[_to] = privateBalance[_to].add(_value);
}
return true;
}
return false;
}
// function to transfer all asset from the old wallet to new wallet. This is used, just in case, the owner forget the private key.
// The owner who which to update the wallet by calling this function must have successfully done KYC and the 6 alpha numeric password
// must be used and submit to Seitee Pte Ltd. The company will recover the old wallet address and transfer the assets to the new wallet
// address on behave of the owner of the wallet address.
function sosTransfer(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password,address _newAddr) onlyOwners public returns(bool){
uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password)));
address oldAddr = kycSOSToOwner[sosHash];
uint256 idx = OwnerToKycData[oldAddr];
require(allowControl[oldAddr] == false);
if(idx > 0)
{
idx = idx - 1;
if(kycDatas[idx].name == _name &&
kycDatas[idx].surName == _surname &&
kycDatas[idx].email == _email &&
kycDatas[idx].password == _password)
{
kycSOSToOwner[sosHash] = _newAddr;
OwnerToKycData[oldAddr] = 0; // reset it
OwnerToKycData[_newAddr] = idx;
kycDataForOwners[idx] = _newAddr;
emit SOSTranfer(oldAddr, _newAddr);
lockAddr[_newAddr] = lockAddr[oldAddr];
//Transfer All Token to new address
balance[_newAddr] = balance[oldAddr];
balance[oldAddr] = 0;
privateBalance[_newAddr] = privateBalance[oldAddr];
privateBalance[oldAddr] = 0;
emit Transfer(oldAddr, _newAddr, balance[_newAddr]);
}
}
return true;
}
// function for internal transfer between wallets that the controls have been given to
// the company (The owner can revoke these controls after ICO closed). Only the founders
// of Seitee Pte Ltd can execute this function. All activities will be publicly logged.
// The user can trace/view the log to check transparency if any founders of the company
// make the transfer of assets from your wallets. Again, Transparency is the key here.
function inTransfer(address _from, address _to,uint256 value) onlyOwners public{
require(allowControl[_from] == true); //default = false
require(balance[_from] >= value);
balance[_from] -= value;
balance[_to] = balance[_to].add(value);
if(privateBalance[_from] <= value)
{
privateBalance[_to] += privateBalance[_from];
privateBalance[_from] = 0;
}
else
{
privateBalance[_from] = privateBalance[_from].sub(value);
privateBalance[_to] = privateBalance[_to].add(value);
}
emit Transfer(_from,_to,value);
}
function balanceOfPrivate(address _walletAddress) public view returns (uint256){
return privateBalance[_walletAddress];
}
}
// Contract for NATEE PRIVATE TOKEN (1 NATEE PRIVATE TOKEN equivalent to 8 NATEE TOKEN)
contract NateePrivate {
function redeemToken(address _redeem, uint256 _value) external;
function getMaxHolder() view external returns(uint256);
function getAddressByID(uint256 _id) view external returns(address);
function balancePrivate(address _walletAddress) public view returns (uint256);
}
// The interface of SGDS (Singapore Dollar Stable)
contract SGDSInterface{
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function intTransfer(address _from, address _to, uint256 _value) external;
function transferWallet(address _from,address _to) external;
function getUserControl(address _addr) external view returns(bool); // if true mean user can control by him. false mean Company can control
function useSGDS(address useAddr,uint256 value) external returns(bool);
function transfer(address _to, uint256 _value) public returns (bool);
}
// Interface of NATEE Warrant
contract NateeWarrantInterface {
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function redeemWarrant(address _from, uint256 _value) external;
function getWarrantInfo() external view returns(string name_,string symbol_,uint256 supply_ );
function getUserControl(address _addr) external view returns(bool);
function sendWarrant(address _to,uint256 _value) external;
function expireDate() public pure returns (uint32);
}
// HAVE 5 Type of REFERRAL
// 1 Buy 8,000 NATEE Then can get referral code REDEEM AFTER REACH SOFTCAP
// 2 FIX RATE REDEEM AFTER REARCH SOFTCAP NO Buy
// 3 adjust RATE REDEEM AFTER REARCH SOFTCAP NO Buy
// 4 adjust RATE REDEEM IMMEDIATLY NO Buy
// 5 FIX RATE REDEEM IMMEDIATLY NO Buy
// Contract for marketing by using referral code from above 5 scenarios.
contract Marketing is MyToken{
struct REFERAL{
uint8 refType;
uint8 fixRate; // user for type 2 and 5
uint256 redeemCom; // summary commision that redeem
uint256 allCommission;
uint256 summaryInvest;
}
REFERAL[] referals;
mapping (address => uint256) referToID;
// Add address for referrer
function addReferal(address _address,uint8 referType,uint8 rate) onlyOwners public{
require(referToID[_address] == 0);
uint256 idx = referals.push(REFERAL(referType,rate,0,0,0));
referToID[_address] = idx;
}
// increase bounty/commission rate for those who has successfully registered the address with this smart contract
function addCommission(address _address,uint256 buyToken) internal{
uint256 idx;
if(referToID[_address] > 0)
{
idx = referToID[_address] - 1;
uint256 refType = uint256(referals[idx].refType);
uint256 fixRate = uint256(referals[idx].fixRate);
if(refType == 1 || refType == 3 || refType == 4){
referals[idx].summaryInvest += buyToken;
if(referals[idx].summaryInvest <= 80000){
referals[idx].allCommission = referals[idx].summaryInvest / 20 / 2; // 5%
}else if(referals[idx].summaryInvest >80000 && referals[idx].summaryInvest <=320000){
referals[idx].allCommission = 2000 + (referals[idx].summaryInvest / 10 / 2); // 10%
}else if(referals[idx].summaryInvest > 320000){
referals[idx].allCommission = 2000 + 12000 + (referals[idx].summaryInvest * 15 / 100 / 2); // 10%
}
}
else if(refType == 2 || refType == 5){
referals[idx].summaryInvest += buyToken;
referals[idx].allCommission = (referals[idx].summaryInvest * 100) * fixRate / 100 / 2;
}
}
}
function getReferByAddr(address _address) onlyOwners view public returns(uint8 refType,
uint8 fixRate,
uint256 commision,
uint256 allCommission,
uint256 summaryInvest){
REFERAL memory refer = referals[referToID[_address]-1];
refType = refer.refType;
fixRate = refer.fixRate;
commision = refer.redeemCom;
allCommission = refer.allCommission;
summaryInvest = refer.summaryInvest;
}
// check if the given address is listed in referral list
function checkHaveRefer(address _address) public view returns(bool){
return (referToID[_address] > 0);
}
// check the total commission on what you have earned so far, the unit is SGDS (Singapore Dollar Stable)
function getCommission(address addr) public view returns(uint256){
require(referToID[addr] > 0);
return referals[referToID[addr] - 1].allCommission;
}
}
// ICO Contract
// 1. Set allocated tokens for sales during pre-sales, prices the duration for pre-sales is 270 days
// 2. Set allocated tokens for sales during public-sales, prices and the duration for public-sales is 90 days.
// 3. The entire duration pre-sales / public sales is no more than 270 days (9 months).
// 4. If the ICO fails to reach Soft Cap, the investors can request for refund by using SGDS and the company will give back into ETH (the exchange rate and ETH price depends on the market)
// 5. There are 2 addresses which will get 1% of fund raised and 5% but not more then 200,000 SGDS . These two addresses helped us in shaping up Business Model and Smart Contract.
contract ICO_Token is Marketing{
uint256 PRE_ICO_ROUND = 20000000 ;
uint256 ICO_ROUND = 40000000 ;
uint256 TOKEN_PRICE = 50; // 0.5 SGDS PER TOKEN
bool startICO; //default = false;
bool icoPass;
bool hardCap;
bool public pauseICO;
uint32 public icoEndTime;
uint32 icoPauseTime;
uint32 icoStartTime;
uint256 totalSell;
uint256 MIN_PRE_ICO_ROUND = 400 ;
uint256 MIN_ICO_ROUND = 400 ;
uint256 MAX_ICO_ROUND = 1000000 ;
uint256 SOFT_CAP = 10000000 ;
uint256 _1Token = 1 ether;
SGDSInterface public sgds;
NateeWarrantInterface public warrant;
mapping (address => uint256) totalBuyICO;
mapping (address => uint256) redeemed;
mapping (address => uint256) redeemPercent;
mapping (address => uint256) redeemMax;
event StartICO(address indexed admin, uint32 startTime,uint32 endTime);
event PassSoftCap(uint32 passTime);
event BuyICO(address indexed addr_,uint256 value);
event BonusWarrant(address indexed,uint256 startRank,uint256 stopRank,uint256 warrantGot);
event RedeemCommision(address indexed, uint256 sgdsValue,uint256 curCom);
event Refund(address indexed,uint256 sgds,uint256 totalBuy);
constructor() public {
//sgds =
//warrant =
pauseICO = false;
icoEndTime = uint32(now + 365 days);
}
function pauseSellICO() onlyOwners external{
require(startICO == true);
require(pauseICO == false);
icoPauseTime = uint32(now);
pauseICO = true;
}
// NEW FUNCTION
function resumeSellICO() onlyOwners external{
require(pauseICO == true);
pauseICO = false;
// Add Time That PAUSE BUT NOT MORE THEN 2 YEAR
uint32 pauseTime = uint32(now) - icoPauseTime;
uint32 maxSellTime = icoStartTime + 730 days;
icoEndTime += pauseTime;
if(icoEndTime > maxSellTime) icoEndTime = maxSellTime;
pauseICO = false;
}
// Function to kicks start the ICO, Auto triggered as soon as the first
// NATEE TOKEN transfer committed.
function startSellICO() internal returns(bool){
require(startICO == false); // IF Start Already it can't call again
icoStartTime = uint32(now);
icoEndTime = uint32(now + 270 days); // ICO 9 month
startICO = true;
emit StartICO(msg.sender,icoStartTime,icoEndTime);
return true;
}
// this function will be executed automatically as soon as Soft Cap reached. By limited additional 90 days
// for public-sales in the total remain days is more than 90 days (the entire ICO takes no more than 270 days).
// For example, if the pre-sales takes 200 days, the public sales duration will be 70 days (270-200).
// Starting from the date that // Soft Cap reached
// if the pre-sales takes 150 days, the public sales duration will be 90 days starting from the date that
// Soft Cap reached
function passSoftCap() internal returns(bool){
icoPass = true;
// after pass softcap will continue sell 90 days
if(icoEndTime - uint32(now) > 90 days)
{
icoEndTime = uint32(now) + 90 days;
}
emit PassSoftCap(uint32(now));
}
// function to refund, this is used when fails to reach Soft CAP and the ICO takes more than 270 days.
// if Soft Cap reached, no refund
function refund() public{
require(icoPass == false);
uint32 maxSellTime = icoStartTime + 730 days;
if(pauseICO == true)
{
if(uint32(now) <= maxSellTime)
{
return;
}
}
if(uint32(now) >= icoEndTime)
{
if(totalBuyICO[msg.sender] > 0)
{
uint256 totalSGDS = totalBuyICO[msg.sender] * TOKEN_PRICE;
uint256 totalNatee = totalBuyICO[msg.sender] * _1Token;
require(totalNatee == balance[msg.sender]);
emit Refund(msg.sender,totalSGDS,totalBuyICO[msg.sender]);
totalBuyICO[msg.sender] = 0;
sgds.transfer(msg.sender,totalSGDS);
}
}
}
// This function is to allow the owner of Wallet Address to set the value (Boolean) to grant/not grant the permission to himself/herself.
// This clearly shows that no one else could set the value to the anyone’s Wallet Address, only msg.sender or the executor of this
// function can set the value in this function.
function userSetAllowControl(bool allow) public{
require(closeICO == true);
allowControl[msg.sender] = allow;
}
// function to calculate the bonus. The bonus will be paid in Warrant according to listed in Bounty section in NATEE Whitepaper
function bonusWarrant(address _addr,uint256 buyToken) internal{
// 1-4M GOT 50%
// 4,000,0001 - 12M GOT 40%
// 12,000,0001 - 20M GOT 30%
// 20,000,0001 - 30M GOT 20%
// 30,000,0001 - 40M GOT 10%
uint256 gotWarrant;
//======= PRE ICO ROUND =============
if(totalSell <= 4000000)
gotWarrant = buyToken / 2; // Got 50%
else if(totalSell >= 4000001 && totalSell <= 12000000)
{
if(totalSell - buyToken < 4000000) // It mean between pre bonus and this bonus
{
gotWarrant = (4000000 - (totalSell - buyToken)) / 2;
gotWarrant += (totalSell - 4000000) * 40 / 100;
}
else
{
gotWarrant = buyToken * 40 / 100;
}
}
else if(totalSell >= 12000001 && totalSell <= 20000000)
{
if(totalSell - buyToken < 4000000)
{
gotWarrant = (4000000 - (totalSell - buyToken)) / 2;
gotWarrant += 2400000; //8000000 * 40 / 100; fix got 2.4 M Token
gotWarrant += (totalSell - 12000000) * 30 / 100;
}
else if(totalSell - buyToken < 12000000 )
{
gotWarrant = (12000000 - (totalSell - buyToken)) * 40 / 100;
gotWarrant += (totalSell - 12000000) * 30 / 100;
}
else
{
gotWarrant = buyToken * 30 / 100;
}
}
else if(totalSell >= 20000001 && totalSell <= 30000000) // public ROUND
{
gotWarrant = buyToken / 5; // 20%
}
else if(totalSell >= 30000001 && totalSell <= 40000000)
{
if(totalSell - buyToken < 30000000)
{
gotWarrant = (30000000 - (totalSell - buyToken)) / 5;
gotWarrant += (totalSell - 30000000) / 10;
}
else
{
gotWarrant = buyToken / 10; // 10%
}
}
else if(totalSell >= 40000001)
{
if(totalSell - buyToken < 40000000)
{
gotWarrant = (40000000 - (totalSell - buyToken)) / 10;
}
else
gotWarrant = 0;
}
//====================================
if(gotWarrant > 0)
{
gotWarrant = gotWarrant * _1Token;
warrant.sendWarrant(_addr,gotWarrant);
emit BonusWarrant(_addr,totalSell - buyToken,totalSell,gotWarrant);
}
}
// NATEE Token can only be purchased by using SGDS
// function to purchase NATEE token, if the purchase transaction committed, the address will be controlled.
// The address wont be able to make any transfer
function buyNateeToken(address _addr, uint256 value,bool refer) onlyOwners external returns(bool){
require(closeICO == false);
require(pauseICO == false);
require(uint32(now) <= icoEndTime);
require(value % 2 == 0); //
if(startICO == false) startSellICO();
uint256 sgdWant;
uint256 buyToken = value;
if(totalSell < PRE_ICO_ROUND) // Still in PRE ICO ROUND
{
require(buyToken >= MIN_PRE_ICO_ROUND);
if(buyToken > PRE_ICO_ROUND - totalSell)
buyToken = uint256(PRE_ICO_ROUND - totalSell);
}
else if(totalSell < PRE_ICO_ROUND + ICO_ROUND)
{
require(buyToken >= MIN_ICO_ROUND);
if(buyToken > MAX_ICO_ROUND) buyToken = MAX_ICO_ROUND;
if(buyToken > (PRE_ICO_ROUND + ICO_ROUND) - totalSell)
buyToken = (PRE_ICO_ROUND + ICO_ROUND) - totalSell;
}
sgdWant = buyToken * TOKEN_PRICE;
require(sgds.balanceOf(_addr) >= sgdWant);
sgds.intTransfer(_addr,address(this),sgdWant); // All SGSD Will Transfer to this account
emit BuyICO(_addr, buyToken * _1Token);
balance[_addr] += buyToken * _1Token;
totalBuyICO[_addr] += buyToken;
//-------------------------------------
// Add TotalSupply HERE
totalSupply_ += buyToken * _1Token;
//-------------------------------------
totalSell += buyToken;
if(totalBuyICO[_addr] >= 8000 && referToID[_addr] == 0)
addReferal(_addr,1,0);
bonusWarrant(_addr,buyToken);
if(totalSell >= SOFT_CAP && icoPass == false) passSoftCap(); // mean just pass softcap
if(totalSell >= PRE_ICO_ROUND + ICO_ROUND && hardCap == false)
{
hardCap = true;
setCloseICO();
}
setAllowControl(_addr);
addHolder(_addr);
if(refer == true)
addCommission(_addr,buyToken);
emit Transfer(address(this),_addr, buyToken * _1Token);
return true;
}
// function to withdraw the earned commission. This depends on type of referral code you holding.
// If Soft Cap pass is required, you will earn SGDS and withdraw the commission to be paid in ETH
function redeemCommision(address addr,uint256 value) public{
require(referToID[addr] > 0);
uint256 idx = referToID[addr] - 1;
uint256 refType = uint256(referals[idx].refType);
if(refType == 1 || refType == 2 || refType == 3)
require(icoPass == true);
require(value > 0);
require(value <= referals[idx].allCommission - referals[idx].redeemCom);
// TRANSFER SGDS TO address
referals[idx].redeemCom += value;
sgds.transfer(addr,value);
emit RedeemCommision(addr,value,referals[idx].allCommission - referals[idx].redeemCom);
}
// check how many tokens sold. This to display on official natee.io website.
function getTotalSell() external view returns(uint256){
return totalSell;
}
// check how many token purchased from the given address.
function getTotalBuyICO(address _addr) external view returns(uint256){
return totalBuyICO[_addr];
}
// VALUE IN SGDS
// Function for AGC and ICZ REDEEM SHARING // 100 % = 10000
function addCOPartner(address addr,uint256 percent,uint256 maxFund) onlyOwners public {
require(redeemPercent[addr] == 0);
redeemPercent[addr] = percent;
redeemMax[addr] = maxFund;
}
function redeemFund(address addr,uint256 value) public {
require(icoPass == true);
require(redeemPercent[addr] > 0);
uint256 maxRedeem;
maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000;
if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr];
require(redeemed[addr] + value <= maxRedeem);
sgds.transfer(addr,value);
redeemed[addr] += value;
}
function checkRedeemFund(address addr) public view returns (uint256) {
uint256 maxRedeem;
maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000;
if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr];
return maxRedeem - redeemed[addr];
}
// Function to close the ICO, this function will transfer the token to founders and advisors
function setCloseICO() public {
require(closeICO == false);
require(startICO == true);
require(icoPass == true);
if(hardCap == false){
require(uint32(now) >= icoEndTime);
}
uint256 lessAdvisor;
uint256 maxAdvisor;
uint256 maxFounder;
uint256 i;
closeICO = true;
// Count Max Advisor
maxAdvisor = 0;
for(i=0;i<advisors.length;i++)
{
if(advisors[i] != address(0))
maxAdvisor++;
}
maxFounder = 0;
for(i=0;i<founders.length;i++)
{
if(founders[i] != address(0))
maxFounder++;
}
TOKEN_PER_ADVISOR = ADVISOR_SUPPLY / maxAdvisor;
// Maximum 200,000 Per Advisor or less
if(TOKEN_PER_ADVISOR > 200000 ether) {
TOKEN_PER_ADVISOR = 200000 ether;
}
lessAdvisor = ADVISOR_SUPPLY - (TOKEN_PER_ADVISOR * maxAdvisor);
// less from Advisor will pay to Founder
TOKEN_PER_FOUNDER = (FOUNDER_SUPPLY + lessAdvisor) / maxFounder;
emit CloseICO();
// Start Send Token to Found and Advisor
for(i=0;i<advisors.length;i++)
{
if(advisors[i] != address(0))
{
balance[advisors[i]] += TOKEN_PER_ADVISOR;
totalSupply_ += TOKEN_PER_ADVISOR;
lockAddress(advisors[i]); // THIS ADDRESS WILL LOCK FOR 2 YEAR CAN'T TRANSFER
addHolder(advisors[i]);
setAllowControl(advisors[i]);
emit Transfer(address(this), advisors[i], TOKEN_PER_ADVISOR);
emit RedeemAdvisor(advisors[i],TOKEN_PER_ADVISOR);
}
}
for(i=0;i<founders.length;i++)
{
if(founders[i] != address(0))
{
balance[founders[i]] += TOKEN_PER_FOUNDER;
totalSupply_ += TOKEN_PER_FOUNDER;
lockAddress(founders[i]);
addHolder(founders[i]);
setAllowControl(founders[i]);
emit Transfer(address(this),founders[i],TOKEN_PER_FOUNDER);
emit RedeemFounder(founders[i],TOKEN_PER_FOUNDER);
}
}
}
}
// main Conttract of NATEE Token, total token is 100 millions and there is no burn token function.
// The token will be auto generated from this function every time after the payment is confirmed
// from the buyer. In short, NATEE token will only be issued, based on the payment.
// There will be no NATEE Token issued in advance. There is no NATEE Token inventory, no stocking,hence,
// there is no need to have the burning function to burn the token/coin in this Smart Contract unlike others ICOs.
contract NATEE is ICO_Token {
using SafeMath256 for uint256;
string public name = "NATEE";
string public symbol = "NATEE"; // Real Name NATEE
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 100000000 ether;
NateePrivate public nateePrivate;
bool privateRedeem;
uint256 public nateeWExcRate = 100; // SGDS Price
uint256 public nateeWExcRateExp = 100; //SGDS Price
address public AGC_ADDR;
address public RM_PRIVATE_INVESTOR_ADDR;
address public ICZ_ADDR;
address public SEITEE_INTERNAL_USE;
event RedeemNatee(address indexed _addr, uint256 _private,uint256 _gotNatee);
event RedeemWarrat(address indexed _addr,address _warrant,string symbole,uint256 value);
constructor() public {
AGC_ADDR = 0xdd25648927291130CBE3f3716A7408182F28b80a; // 1% payment to strategic partne
addCOPartner(AGC_ADDR,100,30000000);
RM_PRIVATE_INVESTOR_ADDR = 0x32F359dE611CFe8f8974606633d8bDCBb33D91CB;
//ICZ is the ICO portal who provides ERC20 solutions and audit NATEE IC
ICZ_ADDR = 0x1F10C47A07BAc12eDe10270bCe1471bcfCEd4Baf; // 5% payment to ICZ capped at 200k SGD
addCOPartner(ICZ_ADDR,500,20000000);
// 20M Internal use to send to NATEE SDK USER
SEITEE_INTERNAL_USE = 0x1219058023bE74FA30C663c4aE135E75019464b4;
balance[RM_PRIVATE_INVESTOR_ADDR] = 3000000 ether;
totalSupply_ += 3000000 ether;
lockAddress(RM_PRIVATE_INVESTOR_ADDR);
setAllowControl(RM_PRIVATE_INVESTOR_ADDR);
addHolder(RM_PRIVATE_INVESTOR_ADDR);
emit Transfer(address(this),RM_PRIVATE_INVESTOR_ADDR,3000000 ether);
balance[SEITEE_INTERNAL_USE] = 20000000 ether;
totalSupply_ += 20000000 ether;
setAllowControl(SEITEE_INTERNAL_USE);
addHolder(SEITEE_INTERNAL_USE);
emit Transfer(address(this),SEITEE_INTERNAL_USE,20000000 ether);
sgds = SGDSInterface(0xf7EfaF88B380469084f3018271A49fF743899C89);
warrant = NateeWarrantInterface(0x7F28D94D8dc94809a3f13e6a6e9d56ad0B6708fe);
nateePrivate = NateePrivate(0x67A9d6d1521E02eCfb4a4C110C673e2c027ec102);
}
// SET SGDS Contract Address
function setSGDSContractAddress(address _addr) onlyOwners external {
sgds = SGDSInterface(_addr);
}
function setNateePrivate(address _addr) onlyOwners external {
nateePrivate = NateePrivate(_addr);
}
function setNateeWarrant(address _addr) onlyOwners external {
warrant = NateeWarrantInterface(_addr);
}
function changeWarrantPrice(uint256 normalPrice,uint256 expPrice) onlyOwners external{
if(uint32(now) < warrant.expireDate())
{
nateeWExcRate = normalPrice;
nateeWExcRateExp = expPrice;
}
}
// function to convert Warrant to NATEE Token, the Warrant holders must have SGDS paid for the conversion fee.
function redeemWarrant(address addr,uint256 value) public returns(bool){
require(owners[msg.sender] == true || addr == msg.sender);
require(closeICO == true);
require(sgds.getUserControl(addr) == false);
uint256 sgdsPerToken;
uint256 totalSGDSUse;
uint256 wRedeem;
uint256 nateeGot;
require(warrant.getUserControl(addr) == false);
if( uint32(now) <= warrant.expireDate())
sgdsPerToken = nateeWExcRate;
else
sgdsPerToken = nateeWExcRateExp;
wRedeem = value / _1Token;
require(wRedeem > 0);
totalSGDSUse = wRedeem * sgdsPerToken;
//check enought SGDS to redeem warrant;
require(sgds.balanceOf(addr) >= totalSGDSUse);
// Start Redeem Warrant;
if(sgds.useSGDS(addr,totalSGDSUse) == true)
{
nateeGot = wRedeem * _1Token;
warrant.redeemWarrant(addr,nateeGot); // duduct Warrant;
balance[addr] += nateeGot;
// =================================
// TOTAL SUPPLY INCREATE
//==================================
totalSupply_ += nateeGot;
//==================================
addHolder(addr);
emit Transfer(address(this),addr,nateeGot);
emit RedeemWarrat(addr,address(warrant),"NATEE-W1",nateeGot);
}
return true;
}
// function to distribute NATEE PRIVATE TOKEN to early investors (from private-sales)
function reddemAllPrivate() onlyOwners public returns(bool){
require(privateRedeem == false);
uint256 maxHolder = nateePrivate.getMaxHolder();
address tempAddr;
uint256 priToken;
uint256 nateeGot;
uint256 i;
for(i=0;i<maxHolder;i++)
{
tempAddr = nateePrivate.getAddressByID(i);
priToken = nateePrivate.balancePrivate(tempAddr);
if(priToken > 0)
{
nateeGot = priToken * 8;
nateePrivate.redeemToken(tempAddr,priToken);
balance[tempAddr] += nateeGot;
totalSupply_ += nateeGot;
privateBalance[tempAddr] += nateeGot;
allowControl[tempAddr] = true;
addHolder(tempAddr);
emit Transfer( address(this), tempAddr, nateeGot);
emit RedeemNatee(tempAddr,priToken,nateeGot);
}
}
privateRedeem = true;
}
} | check how many token purchased from the given address. | function getTotalBuyICO(address _addr) external view returns(uint256){
return totalBuyICO[_addr];
}
| 2,573,319 | [
1,
1893,
3661,
4906,
1147,
5405,
343,
8905,
628,
326,
864,
1758,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
12831,
38,
9835,
2871,
51,
12,
2867,
389,
4793,
13,
3903,
1476,
1135,
12,
11890,
5034,
15329,
203,
202,
202,
2463,
2078,
38,
9835,
2871,
51,
63,
67,
4793,
15533,
203,
202,
97,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43113/0xAE0D28242F42Bc752C5c680Ecf80ce3b43C98E3D/sources/Token02.sol | , "Transfer amount must be greater than zero");
| require(amount > 0); | 13,188,330 | [
1,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2583,
12,
8949,
405,
374,
1769,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.