file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/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 no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: SpoderUniverseV2.sol
pragma solidity ^0.8.0;
contract SpoderBytesHeritage {
function walletOfOwner(address _owner) external view returns (uint256[] memory) {}
}
contract SpoderBytesSeasonal {
function walletOfOwner(address _owner) external view returns (uint256[] memory) {}
}
contract SpoderBytesUniverse is
ERC721Enumerable,
Ownable
{
SpoderBytesHeritage spoderHeritageContract;
SpoderBytesSeasonal spoderSeasonalContract;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
using SafeMath for uint256;
uint256 private MAX_ELEMENTS = 7737;
uint256 private constant PRICE = 1.5 * 10**14;
uint256 private constant MAX_BY_MINT = 20;
address private PAYABLEWALLET = 0xaf93C95201866586c4d76E5182073067Bc05a922;
string public baseTokenURI;
mapping (address=>bool) public _whiteListHasMinted;
bool private _mainSalePaused = true;
bool private _whiteListPaused = true;
event CreateSpoder(address minter, uint256 minted);
constructor(string memory baseURI, address _heritageContract, address _seasonalContract)
ERC721("Spoder-Universe", "SPOU")
{
setBaseURI(baseURI);
spoderHeritageContract = SpoderBytesHeritage(_heritageContract);
spoderSeasonalContract = SpoderBytesSeasonal(_seasonalContract);
}
function setSpoderContracts(address _newHeritageContract, address _newSeasonalContract) public onlyOwner {
spoderHeritageContract = SpoderBytesHeritage(_newHeritageContract);
spoderSeasonalContract = SpoderBytesSeasonal(_newSeasonalContract);
}
function setPauseMainSale(bool _newPause) public onlyOwner {
_mainSalePaused = _newPause;
}
function setPauseWhiteList(bool _newPause) public onlyOwner {
_whiteListPaused = _newPause;
}
function isMainSaleActive() public view returns (bool) {
if(totalSupply() < MAX_ELEMENTS && _mainSalePaused == false)
{
return true;
} else {
return false;
}
}
function isWhitelistSaleActive() public view returns (bool) {
if(totalSupply() < MAX_ELEMENTS && _whiteListPaused == false)
{
return true;
} else {
return false;
}
}
function mint(uint256 _count) public payable {
require(_mainSalePaused == false, "Sale not active.");
require(_count > 0, "Mint needs to be greater than 0");
require(_count <= MAX_BY_MINT, "Minting too many");
require(totalSupply() < MAX_ELEMENTS, "Sale has ended");
require(totalSupply() + _count <= MAX_ELEMENTS, "Minting too many");
require(msg.value >= (PRICE * _count), "Not enough ETH");
for (uint j = 0; j<_count; j++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
emit CreateSpoder(msg.sender, newItemId);
}
}
function whiteListMint(uint256 _count, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
require(_whiteListPaused == false, "Sale not active.");
require(_count > 0, "Mint needs to be greater than 0");
require(_count <= MAX_BY_MINT, "Minting too many");
require(totalSupply() < MAX_ELEMENTS, "Sale has ended");
require(totalSupply() + _count <= MAX_ELEMENTS, "Minting too many");
require(msg.value >= (PRICE * _count), "Not enough ETH");
//Check to see if eligible for 1 Free mint per spoder per existing Heritage/Spooky spoders owned
if(_whiteListHasMinted[msg.sender] == false)
{
uint256 ExistingOwnerAmt = 0;
ExistingOwnerAmt = spoderHeritageContract.walletOfOwner(msg.sender).length;
ExistingOwnerAmt = ExistingOwnerAmt + spoderSeasonalContract.walletOfOwner(msg.sender).length;
//Check to make sure we're not going over supply
require(totalSupply() + _count + ExistingOwnerAmt <= MAX_ELEMENTS, "Minting too many");
if(ExistingOwnerAmt > 0)
{
//Mint Free Spoders
for (uint j = 0; j<ExistingOwnerAmt; j++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
emit CreateSpoder(msg.sender, newItemId);
}
}
}
for (uint j = 0; j<_count; j++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
emit CreateSpoder(msg.sender, newItemId);
}
_whiteListHasMinted[msg.sender] = true;
}
function freeMint(uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
require(_whiteListPaused == false, "Sale not active.");
require(totalSupply() < MAX_ELEMENTS, "Sale has ended");
require(_whiteListHasMinted[msg.sender] == false, "User has already minted");
require(spoderHeritageContract.walletOfOwner(msg.sender).length > 0 || spoderSeasonalContract.walletOfOwner(msg.sender).length > 0, "Not Whitelisted");
uint256 ExistingOwnerAmt = 0;
ExistingOwnerAmt = spoderHeritageContract.walletOfOwner(msg.sender).length;
ExistingOwnerAmt = ExistingOwnerAmt + spoderSeasonalContract.walletOfOwner(msg.sender).length;
//Check to make sure we're not going over supply
require(totalSupply() + ExistingOwnerAmt <= MAX_ELEMENTS, "Minting too many");
if(ExistingOwnerAmt > 0)
{
//Mint Free Spoders
for (uint j = 0; j<ExistingOwnerAmt; j++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
emit CreateSpoder(msg.sender, newItemId);
}
}
_whiteListHasMinted[msg.sender] = true;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
function setMaxSupply(uint256 _supply) public onlyOwner {
MAX_ELEMENTS = _supply;
}
function setPayableWallet(address _newWallet) public onlyOwner {
PAYABLEWALLET = _newWallet;
}
function walletOfOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdrawAll() public payable onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0);
_withdraw(PAYABLEWALLET, address(this).balance);
}
function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
modifier onlyValidAccess(uint8 _v, bytes32 _r, bytes32 _s)
{
require(isValidAccessMessage(msg.sender,_v,_r,_s), "Not Whitelisted");
_;
}
function isValidAccessMessage(address _add, uint8 _v, bytes32 _r, bytes32 _s) public view returns (bool)
{
bytes32 hash = keccak256(abi.encodePacked(address(this), _add));
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
return owner() == ecrecover(keccak256(abi.encodePacked(prefix, hash)),_v,_r,_s);
}
}
|
Check to make sure we're not going over supplyMint Free Spoders
|
function freeMint(uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
require(_whiteListPaused == false, "Sale not active.");
require(totalSupply() < MAX_ELEMENTS, "Sale has ended");
require(_whiteListHasMinted[msg.sender] == false, "User has already minted");
require(spoderHeritageContract.walletOfOwner(msg.sender).length > 0 || spoderSeasonalContract.walletOfOwner(msg.sender).length > 0, "Not Whitelisted");
uint256 ExistingOwnerAmt = 0;
ExistingOwnerAmt = spoderHeritageContract.walletOfOwner(msg.sender).length;
ExistingOwnerAmt = ExistingOwnerAmt + spoderSeasonalContract.walletOfOwner(msg.sender).length;
require(totalSupply() + ExistingOwnerAmt <= MAX_ELEMENTS, "Minting too many");
if(ExistingOwnerAmt > 0)
{
for (uint j = 0; j<ExistingOwnerAmt; j++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
emit CreateSpoder(msg.sender, newItemId);
}
}
_whiteListHasMinted[msg.sender] = true;
}
| 1,486,251 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/AddressUtils.sol";
import "./CvcEscrowInterface.sol";
import "../pricing/CvcPricingInterface.sol";
import "../upgradeability/Initializable.sol";
import "../upgradeability/EternalStorage.sol";
import "../upgradeability/Pausable.sol";
/**
* @title CvcEscrow
* @dev This contract provides escrow service functionality for the Identity.com marketplace.
* It controls an escrow placement's lifecycle which involves transferring a pre-approved amount funds
* from the Identity Requester account to its own account and keeping them until the marketplace deal is complete.
*
* Glossary:
* Identity Requester (IDR) - Business entities requesting verifiable Credentials from a user in order to authenticate them.
* Identity Validator (IDV) - Businesses or organizations that validate a user's identity and provide verifiable credentials.
* Scope Request - A request for identity information about a user from an IDR to an IDV.
* Credential Item - A single item in a set of verifiable credentials that an IDR can specify within a scope request.
*
* The marketplace flow has 2 possible outcomes:
* 1. release - when user's personally identifiable information (PII) has been delivered to Identity Requester.
* In this case the release functionality is triggered and the contract transfers escrowed funds
* to the Identity Validator account, excluding the marketplace fee (if applied).
*
* 2. cancellation - when user's personally identifiable information (PII) has NOT been delivered to Identity Requester.
* In this case the refund procedure can be executed and all the escrowed funds will be returned
* back to Identity Requester account.
*
* The escrow contract depends on other marketplace contracts, such as:
* CvcToken - to perform CVC transfers.
* CvcPricing - to check the actual marketplace prices and ensure that placed amount of tokens
* covers the Credential Items price and matches the expectation of all involved parties.
*/
contract CvcEscrow is EternalStorage, Initializable, Pausable, CvcEscrowInterface {
using SafeMath for uint256;
/**
Data structures and storage layout:
struct EscrowPlacement {
uint256 state;
uint256 amount;
uint256 credentialItemIdsCount;
bytes32[] credentialItemIds;
uint256 blockNumber;
}
uint256 timeoutThreshold;
uint256 platformFeeRate;
address cvcToken;
address cvcPricing;
address platform;
mapping(bytes32 => EscrowPlacement) placements;
**/
/// The divisor for calculating platform fee rate.
/// Solidity does not support floats,
/// so we provide rather big unsigned integer and then divide it by this constant
uint256 constant public RATE_PRECISION = 1e8;
/**
* @dev Constructor
* @param _token CVC Token contract address
* @param _platform Platform address to send retained fee to
* @param _pricing Pricing contract address to lookup for escrow amount before placing
*/
constructor(address _token, address _platform, address _pricing) public {
initialize(_token, _platform, _pricing, msg.sender);
}
/**
* @dev Handles escrow placement for a single scope request.
* @param _idv Address of Identity Validator
* @param _scopeRequestId Scope request identifier
* @param _amount CVC token amount in creds (CVC x 10e-8)
* @param _credentialItemIds Array of credential item IDs
* @return bytes32 New Placement ID
*/
function place(
address _idv,
bytes32 _scopeRequestId,
uint256 _amount,
bytes32[] _credentialItemIds
)
external
onlyInitialized
whenNotPaused
returns (bytes32)
{
// Prepare a batch with single scope request ID.
bytes32[] memory scopeRequestIds = new bytes32[](1);
scopeRequestIds[0] = _scopeRequestId;
return makePlacement(_idv, scopeRequestIds, _amount, _credentialItemIds);
}
/**
* @dev Handles escrow placement for multiple scope requests grouped by credential item IDs.
* @param _idv Address of Identity Validator
* @param _scopeRequestIds Array of scope request IDs
* @param _amount CVC token amount in creds (CVC x 10e-8)
* @param _credentialItemIds Array of credential item IDs
* @return bytes32 New Placement ID
*/
function placeBatch(address _idv, bytes32[] _scopeRequestIds, uint256 _amount, bytes32[] _credentialItemIds)
external
onlyInitialized
whenNotPaused
returns (bytes32)
{
return makePlacement(_idv, _scopeRequestIds, _amount, _credentialItemIds);
}
/**
* @dev Releases escrow placement and distributes funds.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _scopeRequestId Scope request identifier
*/
function release(address _idr, address _idv, bytes32 _scopeRequestId)
external
onlyOwner
onlyInitialized
whenNotPaused
{
// Prepare a batch with single scope request ID.
bytes32[] memory scopeRequestIdsToRelease = new bytes32[](1);
scopeRequestIdsToRelease[0] = _scopeRequestId;
// itemsToKeep is empty to indicate full release.
makePartialRelease(_idr, _idv, scopeRequestIdsToRelease, new bytes32[](0));
}
/**
* @dev Releases escrow placement for multiple scope requests and distributes funds.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _scopeRequestIdsToRelease Array of scope request IDs which will be released
* @param _scopeRequestIdsToKeep Array of scope request IDs which will be kept in escrow
* @return bytes32 Placement ID of remaining part of the batch. Empty when the placement was fully released
*/
function releaseBatch(
address _idr,
address _idv,
bytes32[] _scopeRequestIdsToRelease,
bytes32[] _scopeRequestIdsToKeep
)
external
onlyOwner
onlyInitialized
whenNotPaused
returns (bytes32)
{
return makePartialRelease(_idr, _idv, _scopeRequestIdsToRelease, _scopeRequestIdsToKeep);
}
/**
* @dev Refunds escrowed tokens for a single scope request back to Identity Requester.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _scopeRequestId Scope request ID
*/
function refund(address _idr, address _idv, bytes32 _scopeRequestId) external onlyInitialized whenNotPaused {
// Prepare a batch with single scope request ID.
bytes32[] memory scopeRequestIds = new bytes32[](1);
scopeRequestIds[0] = _scopeRequestId;
makeFullRefund(_idr, _idv, scopeRequestIds);
}
/**
* @dev Refunds escrowed tokens for for multiple scope requests back to Identity Requester.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _scopeRequestIds Array of scope request IDs
*/
function refundBatch(address _idr, address _idv, bytes32[] _scopeRequestIds)
external
onlyInitialized
whenNotPaused
{
makeFullRefund(_idr, _idv, _scopeRequestIds);
}
/**
* @dev Returns placement details.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _scopeRequestId Scope request ID
* @return uint256 CVC token amount in creds (CVC x 10e-8)
* @return PlacementState One of the CvcEscrowInterface.PlacementState values
* @return bytes32[] Array of credential item IDs
* @return uint256 Block confirmations since escrow was placed
* @return bool True if placement can be refunded otherwise false
*/
function verify(address _idr, address _idv, bytes32 _scopeRequestId)
external
view
returns (
uint256 placementAmount,
PlacementState placementState,
bytes32[] credentialItemIds,
uint256 confirmations,
bool refundable
)
{
// Prepare a batch with single scope request ID.
bytes32[] memory scopeRequestIds = new bytes32[](1);
scopeRequestIds[0] = _scopeRequestId;
return getPlacement(calculatePlacementId(_idr, _idv, scopeRequestIds));
}
/**
* @dev Returns placement details.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _scopeRequestIds Array of scope request IDs
* @return uint256 CVC token amount in creds (CVC x 10e-8)
* @return PlacementState One of the CvcEscrowInterface.PlacementState values
* @return bytes32[] Array of credential item IDs
* @return uint256 Block confirmations since escrow was placed
* @return bool True if placement can be refunded otherwise false
*/
function verifyBatch(address _idr, address _idv, bytes32[] _scopeRequestIds)
external
view
returns (
uint256 placementAmount,
PlacementState placementState,
bytes32[] credentialItemIds,
uint256 confirmations,
bool refundable
)
{
return getPlacement(calculatePlacementId(_idr, _idv, _scopeRequestIds));
}
/**
* @dev Returns placement details.
* @param _placementId Escrow Placement identifier.
* @return uint256 CVC token amount in creds (CVC x 10e-8)
* @return PlacementState One of the CvcEscrowInterface.PlacementState values.
* @return bytes32[] Array of credential item IDs.
* @return uint256 Block confirmations since escrow was placed.
* @return bool True if placement can be refunded otherwise false
*/
function verifyPlacement(bytes32 _placementId)
external
view
returns (
uint256 placementAmount,
PlacementState placementState,
bytes32[] credentialItemIds,
uint256 confirmations,
bool refundable
)
{
return getPlacement(_placementId);
}
/**
* @dev Contract initialization method.
* @param _token CVC Token contract address
* @param _platform Platform address to send retained fee to
* @param _pricing Pricing contract address to lookup for escrow amount before placing
* @param _owner Owner address, used for release
*/
function initialize(address _token, address _platform, address _pricing, address _owner)
public
initializes
{
// Ensure contracts.
require(AddressUtils.isContract(_token), "Initialization error: no contract code at token contract address");
require(AddressUtils.isContract(_pricing), "Initialization error: no contract code at pricing contract address");
/// Timeout value for escrowed funds before refund is available.
/// Currently represents number of blocks for approx 24 hours.
// timeoutThreshold = 5800;
uintStorage[keccak256("timeout.threshold")] = 5800;
/// The percentage of escrowed funds retained as a platform fee.
/// The default rate is 10% (0.1 * 10^8).
// platformFeeRate = 1e7;
uintStorage[keccak256("platform.fee.rate")] = 1e7;
// Initialize current implementation owner address.
setOwner(_owner);
// CVC Token contract address to transfer CVC tokens.
// cvcToken = _token;
addressStorage[keccak256("cvc.token")] = _token;
// Pricing contract address to lookup attestation prices.
// cvcPricing = _pricing;
addressStorage[keccak256("cvc.pricing")] = _pricing;
// Platform address is used to transfer platform usage fee.
// platform = _platform;
addressStorage[keccak256("platform")] = _platform;
}
/**
* @dev Calculates escrow placement identifier.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _scopeRequestIds An array of scope request identifiers
* @return bytes32 Placement ID
*/
function calculatePlacementId(address _idr, address _idv, bytes32[] _scopeRequestIds)
public
pure
returns (bytes32)
{
require(_idr != address(0), "Cannot calculate placement ID with IDR being a zero address");
require(_idv != address(0), "Cannot calculate placement ID with IDV being a zero address");
return keccak256(abi.encodePacked(_idr, _idv, calculateBatchReference(_scopeRequestIds)));
}
/**
* @dev Returns platform fee amount based on given placement amount and current platform fee rate.
* @param _amount Escrow placement total amount.
* @return uint256
*/
function calculatePlatformFee(uint256 _amount) public view returns (uint256) {
return (_amount.mul(platformFeeRate()).add(RATE_PRECISION.div(2))).div(RATE_PRECISION);
}
/**
* @dev Sets timeout threshold. Ensures it's more than 0.
* @param _threshold New timeout threshold value
*/
function setTimeoutThreshold(uint256 _threshold) public onlyOwner onlyInitialized {
require(_threshold > 0, "Timeout threshold cannot be zero");
// timeoutThreshold = _threshold;
uintStorage[keccak256("timeout.threshold")] = _threshold;
}
/**
* @dev Returns actual escrow timeout threshold value.
* @return uint256
*/
function timeoutThreshold() public view returns (uint256) {
// return timeoutThreshold;
return uintStorage[keccak256("timeout.threshold")];
}
/**
* @dev Allows to change platform fee rate.
* @param _feeRate A platform fee rate in percentage, e.g. 1e7 (10%).
*/
function setFeeRate(uint256 _feeRate) public onlyOwner onlyInitialized {
require(_feeRate <= RATE_PRECISION, "Platform fee rate cannot be more than 100%");
// platformFeeRate = _feeRate;
uintStorage[keccak256("platform.fee.rate")] = _feeRate;
}
/**
* @dev Returns actual platform fee rate value.
* @return uint256
*/
function platformFeeRate() public view returns (uint256) {
// return platformFeeRate;
return uintStorage[keccak256("platform.fee.rate")];
}
/**
* @dev Returns CvcToken contact instance.
* @return ERC20
*/
function token() public view returns (ERC20) {
// return ERC20(cvcToken);
return ERC20(addressStorage[keccak256("cvc.token")]);
}
/**
* @dev Returns CvcPricing contact instance.
* @return CvcPricingInterface
*/
function pricing() public view returns (CvcPricingInterface) {
// return CvcPricingInterface(cvcPricing);
return CvcPricingInterface(addressStorage[keccak256("cvc.pricing")]);
}
/**
* @dev Returns platform address.
* @return address
*/
function platformAddress() public view returns (address) {
// return platform;
return addressStorage[keccak256("platform")];
}
/**
* @dev Stores placement data against the placement ID.
* @param _placementId Unique placement identifier
* @param _amount CVC token amount in creds (CVC x 10e-8)
* @param _credentialItemIds Array of credential item IDs
* @param _blockNumber Block number at which the placement is received
*/
function saveNewPlacement(bytes32 _placementId, uint256 _amount, bytes32[] _credentialItemIds, uint256 _blockNumber)
internal
{
// Verify current state for given placementId to ensure operation is allowed.
PlacementState placementState = getPlacementState(_placementId);
// Placement is allowed when:
// 1. it is a completely new escrow placement with fresh ID (Empty state)
// 2. the placement with given ID was refunded (Canceled state)
require(
placementState == PlacementState.Empty || placementState == PlacementState.Canceled,
"Invalid placement state: must be new or canceled"
);
// Write placement data into the contract storage.
setPlacementState(_placementId, PlacementState.Placed);
setPlacementCredentialItemIds(_placementId, _credentialItemIds);
setPlacementAmount(_placementId, _amount);
setPlacementBlockNumber(_placementId, _blockNumber);
}
/**
* @dev Returns placement total price based on number of credential items and their current market prices.
* @param _idv Identity Validator address
* @param _credentialItemIds Array of credential item IDs
* @param _batchSize Number of scope request IDs in placement
* @return uint256
*/
function getPlacementPrice(address _idv, bytes32[] _credentialItemIds, uint256 _batchSize)
internal
view
returns (uint256)
{
uint256 price = 0;
uint256 credentialItemPrice;
CvcPricingInterface cvcPricing = pricing();
for (uint256 i = 0; i < _credentialItemIds.length; i++) {
(, credentialItemPrice, , , , ,) = cvcPricing.getPriceByCredentialItemId(_idv, _credentialItemIds[i]);
price = price.add(credentialItemPrice);
}
return price.mul(_batchSize);
}
/**
* @dev Check if the escrow placement can be refunded back to Identity Requester.
* @param _placementState The escrow placement state.
* @param _placementBlockNumber The escrow placement block number.
* @return bool Whether escrow can be refunded.
*/
function isRefundable(PlacementState _placementState, uint256 _placementBlockNumber) internal view returns (bool) {
// Refund is allowed if the escrowed placement is still in "Placed" state & timeout is reached.
// Timeout reached when number of blocks after the escrow was placed is greater than timeout threshold.
return _placementState == PlacementState.Placed && block.number.sub(_placementBlockNumber) > timeoutThreshold();
}
/**
* @dev Transfers funds from IRD account and stores the placement data.
* @param _idv Address of Identity Validator
* @param _scopeRequestIds Array of scope request IDs
* @param _amount CVC token amount in creds (CVC x 10e-8)
* @param _credentialItemIds Array of credential item IDs
* @return bytes32 New Placement ID
*/
function makePlacement(address _idv, bytes32[] _scopeRequestIds, uint256 _amount, bytes32[] _credentialItemIds)
internal
returns (bytes32)
{
// Calculate placement ID to validate arguments.
bytes32 placementId = calculatePlacementId(msg.sender, _idv, _scopeRequestIds);
// Ensure escrow amount is matching the total price of all credential items.
require(
_amount == getPlacementPrice(_idv, _credentialItemIds, _scopeRequestIds.length),
"Placement amount does not match credential item total price"
);
// Store new placement data.
saveNewPlacement(placementId, _amount, _credentialItemIds, block.number);
// Transferring funds from IDR to escrow contract address.
require(token().transferFrom(msg.sender, this, _amount), "Token transfer from IDR account failed");
// Emitting escrow placement event for each individual scope request ID.
uint256 amountPerItem = _amount.div(_scopeRequestIds.length);
for (uint256 i = 0; i < _scopeRequestIds.length; i++) {
emit EscrowPlaced(msg.sender, _idv, _scopeRequestIds[i], amountPerItem, _credentialItemIds, placementId);
}
return placementId;
}
/**
* @dev Calculates scope request batch reference.
* @param _scopeRequestIds An array of scope request identifiers
* @return bytes32 Batch reference
*/
function calculateBatchReference(bytes32[] _scopeRequestIds)
internal
pure
returns (bytes32 batchReference)
{
// In order to increase batch reference entropy and prevent potential collision
// caused by small difference between two or more scope request IDs from the same batch
// we hash the scope request ID before adding to the batch reference.
for (uint256 i = 0; i < _scopeRequestIds.length; i++) {
// Ensure scopeRequestId is not empty & add its hash to batch reference.
require(_scopeRequestIds[i] != 0x0, "Cannot calculate batch reference with empty scope request ID");
batchReference = batchReference ^ keccak256(abi.encodePacked(_scopeRequestIds[i]));
}
}
/**
* @dev Releases placed batch items.
* In case of partial release keeps the remaining part in escrow under new placement ID.
* If the entire batch is release, empty bytes returned instead.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _itemsToRelease Array of scope request IDs to be released
* @param _itemsToKeep Array of scope request IDs to keep in escrow
* @return bytes32 Placement ID of remaining part of the batch. Empty when the placement was fully released
*/
function makePartialRelease(address _idr, address _idv, bytes32[] _itemsToRelease, bytes32[] _itemsToKeep)
internal
returns (bytes32)
{
// Restore initial placement ID.
bytes32 batchReference = calculateBatchReference(_itemsToRelease);
if (_itemsToKeep.length > 0) {
batchReference = batchReference ^ calculateBatchReference(_itemsToKeep);
}
bytes32 placementId = keccak256(abi.encodePacked(_idr, _idv, batchReference));
// Allow release only when the escrow exists and it is not refundable yet.
// If placement found by ID, we can be sure two arrays of scope request IDs together formed the initial batch.
PlacementState placementState = getPlacementState(placementId);
require(placementState == PlacementState.Placed, "Invalid placement state: must be placed");
require(!isRefundable(placementState, getPlacementBlockNumber(placementId)), "Timed out: release is not possible anymore");
// Change placement state to released.
setPlacementState(placementId, PlacementState.Released);
// Calculate released token amount.
uint256 totalBatchSize = _itemsToRelease.length.add(_itemsToKeep.length);
uint256 placementAmount = getPlacementAmount(placementId);
uint256 amountToRelease = placementAmount.mul(_itemsToRelease.length).div(totalBatchSize);
// Release batch items and distribute escrowed funds.
releaseEscrowedFunds(placementId, _idr, _idv, _itemsToRelease, amountToRelease);
// Return empty bytes when the entire batch released.
if (_itemsToKeep.length == 0)
return 0x0;
// Keep the remaining part of the batch in escrow.
uint256 amountToKeep = placementAmount.mul(_itemsToKeep.length).div(totalBatchSize);
return keepPlacement(placementId, _idr, _idv, _itemsToKeep, amountToKeep);
}
/**
* @dev Refunds escrowed tokens for for multiple scope requests back to Identity Requester.
* @param _idr Address of Identity Requester
* @param _idv Address of Identity Validator
* @param _itemsToRefund Array of scope request IDs to be refunded
*/
function makeFullRefund(address _idr, address _idv, bytes32[] _itemsToRefund) internal {
// Calculate placement ID to validate arguments.
bytes32 placementId = calculatePlacementId(_idr, _idv, _itemsToRefund);
// Check if refund is allowed.
require(
isRefundable(getPlacementState(placementId), getPlacementBlockNumber(placementId)),
"Placement is not refundable yet"
);
// Mark the escrow placement Canceled.
setPlacementState(placementId, PlacementState.Canceled);
// Transfer funds from the escrow contract balance to IDR account.
uint256 placementAmount = getPlacementAmount(placementId);
require(token().transfer(_idr, placementAmount), "Token transfer to IDR account failed");
// Emitting escrow cancellation event for each individual scope request ID.
uint256 amountPerItem = placementAmount.div(_itemsToRefund.length);
bytes32[] memory credentialItemIds = getPlacementCredentialItemIds(placementId);
for (uint256 i = 0; i < _itemsToRefund.length; i++) {
emit EscrowCanceled(_idr, _idv, _itemsToRefund[i], amountPerItem, credentialItemIds, placementId);
}
}
/**
* @dev Stores items as a new placement.
* @param _placementId Current placement identifier.
* @param _idr Address of Identity Requester.
* @param _idv Address of Identity Validator.
* @param _itemsToKeep Array of scope request IDs to keep in escrow.
* @param _amount New Placement amount.
* @return bytes32 New Placement ID.
*/
function keepPlacement(bytes32 _placementId, address _idr, address _idv, bytes32[] _itemsToKeep, uint256 _amount)
internal
returns (bytes32)
{
// Calculate new placement ID.
bytes32 newPlacementId = calculatePlacementId(_idr, _idv, _itemsToKeep);
// Store data against new placement ID. Copy unchanged data from old placement.
bytes32[] memory credentialItemIds = getPlacementCredentialItemIds(_placementId);
saveNewPlacement(newPlacementId, _amount, credentialItemIds, getPlacementBlockNumber(_placementId));
uint256 amountPerItem = _amount.div(_itemsToKeep.length);
for (uint256 i = 0; i < _itemsToKeep.length; i++) {
emit EscrowMoved(_idr, _idv, _itemsToKeep[i], amountPerItem, credentialItemIds, _placementId, newPlacementId);
}
return newPlacementId;
}
/**
* @dev Transfers funds to IDV withholding platform fee (if applied).
* @param _placementId Released placement identifier.
* @param _idr Address of Identity Requester.
* @param _idv Address of Identity Validator.
* @param _releasedItems Array of released scope request IDs.
* @param _amount Amount to release.
*/
function releaseEscrowedFunds(bytes32 _placementId, address _idr, address _idv, bytes32[] _releasedItems, uint256 _amount)
internal
{
// Calculate token distribution.
uint256 platformFee = calculatePlatformFee(_amount);
uint256 idvFee = platformFee > 0 ? _amount.sub(platformFee) : _amount;
// Transfer tokens from escrow to IDV.
ERC20 cvcToken = token();
require(cvcToken.transfer(_idv, idvFee), "Token transfer to IDV account failed");
// Transfer tokens from escrow to platform operator address.
if (platformFee > 0) {
require(cvcToken.transfer(platformAddress(), platformFee), "Token transfer to platform account failed");
}
logBatchRelease(
_placementId,
_idr,
_idv,
_releasedItems,
platformFee.div(_releasedItems.length),
idvFee.div(_releasedItems.length)
);
}
/**
* @dev Emits EscrowReleased event for each released item.
* @param _placementId Released placement identifier.
* @param _idr Address of Identity Requester.
* @param _idv Address of Identity Validator.
* @param _releasedItems Array of released scope request IDs.
* @param _itemPlatformFee Platform fee charged per one item.
* @param _itemIdvFee Identity Validator fee charged per one item.
*/
function logBatchRelease(
bytes32 _placementId,
address _idr,
address _idv,
bytes32[] _releasedItems,
uint256 _itemPlatformFee,
uint256 _itemIdvFee
)
internal
{
bytes32[] memory credentialItemIds = getPlacementCredentialItemIds(_placementId);
for (uint256 i = 0; i < _releasedItems.length; i++) {
emit EscrowReleased(
_idr,
_idv,
_releasedItems[i],
_itemPlatformFee,
_itemIdvFee,
credentialItemIds,
_placementId
);
}
}
/**
* @dev Returns placement details.
* @param _placementId Escrow Placement identifier.
* @return uint256 CVC token amount in creds (CVC x 10e-8)
* @return PlacementState One of the CvcEscrowInterface.PlacementState values.
* @return bytes32[] Array of credential item IDs.
* @return uint256 Block confirmations since escrow was placed.
* @return bool True if placement can be refunded otherwise false
*/
function getPlacement(bytes32 _placementId)
internal
view
returns (
uint256 placementAmount,
PlacementState placementState,
bytes32[] credentialItemIds,
uint256 confirmations,
bool refundable
)
{
placementState = getPlacementState(_placementId);
// Placement amount value is returned for Placed placements, otherwise 0;
placementAmount = placementState == PlacementState.Placed ? getPlacementAmount(_placementId) : 0;
credentialItemIds = getPlacementCredentialItemIds(_placementId);
// 0 when empty, number of blocks in other states
uint256 placementBlockNumber = getPlacementBlockNumber(_placementId);
confirmations = placementState == PlacementState.Empty ? 0 : block.number.sub(placementBlockNumber);
refundable = isRefundable(placementState, placementBlockNumber);
}
/**
* @dev Returns placement state.
* @param _placementId The placement ID.
* @return PlacementState
*/
function getPlacementState(bytes32 _placementId) internal view returns (PlacementState) {
// return PlacementState(placements[_placementId].state);
return PlacementState(uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".state"))]);
}
/**
* @dev Saves placement state.
* @param _placementId The placement ID.
* @param state Placement state.
*/
function setPlacementState(bytes32 _placementId, PlacementState state) internal {
// placements[_placementId].state = uint256(state);
uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".state"))] = uint256(state);
}
/**
* @dev Returns placement amount.
* @param _placementId The placement ID.
* @return uint256
*/
function getPlacementAmount(bytes32 _placementId) internal view returns (uint256) {
// return placements[_placementId].amount;
return uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".amount"))];
}
/**
* @dev Saves placement amount.
* @param _placementId The placement ID.
* @param _amount Placement amount.
*/
function setPlacementAmount(bytes32 _placementId, uint256 _amount) internal {
// placements[_placementId].amount = _amount;
uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".amount"))] = _amount;
}
/**
* @dev Returns placement credential item IDs.
* @param _placementId The placement ID.
* @return bytes32[] Array of credential item IDs.
*/
function getPlacementCredentialItemIds(bytes32 _placementId)
internal
view
returns (bytes32[])
{
// uint256 count = placements[_placementId].credentialItemIdsCount;
uint256 count = uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds"))];
bytes32[] memory credentialItemIds = new bytes32[](count);
for (uint256 i = 0; i < count; i++) {
// credentialItemIds[i] = placements[_placementId].credentialItemIds[i];
credentialItemIds[i] = bytes32Storage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds.", i))];
}
return credentialItemIds;
}
/**
* @dev Saves placement credential item IDs.
* @param _placementId The placement ID.
* @param _credentialItemIds Array of credential item IDs.
*/
function setPlacementCredentialItemIds(bytes32 _placementId, bytes32[] _credentialItemIds) internal
{
// placements[_placementId].credentialItemIdsCount = _credentialItemIds.length;
uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds"))] = _credentialItemIds.length;
for (uint256 i = 0; i < _credentialItemIds.length; i++) {
// placements[_placementId].credentialItemIds[i] = _credentialItemIds[i];
bytes32Storage[keccak256(abi.encodePacked("placements.", _placementId, ".credentialItemIds.", i))] = _credentialItemIds[i];
}
}
/**
* @dev Returns placement block number.
* @param _placementId The placement ID.
* @return uint256
*/
function getPlacementBlockNumber(bytes32 _placementId) internal view returns (uint256) {
// return placements[_placementId].blockNumber;
return uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".blockNumber"))];
}
/**
* @dev Saves placement block number.
* @param _placementId The placement ID.
* @param _blockNumber Placement block number.
*/
function setPlacementBlockNumber(bytes32 _placementId, uint256 _blockNumber) internal {
// placements[_placementId].blockNumber = _blockNumber;
uintStorage[keccak256(abi.encodePacked("placements.", _placementId, ".blockNumber"))] = _blockNumber;
}
}
|
Returns actual platform fee rate value. return uint256/ return platformFeeRate;
|
function platformFeeRate() public view returns (uint256) {
return uintStorage[keccak256("platform.fee.rate")];
}
| 6,411,408 |
pragma solidity >=0.4.21 <0.7.0;
contract Review {
// Saving address for reviewers that have already voted
address[4] public reviewers;
// Mapp address to bool[], in order to record the panel that has already submitted
mapping(address => bool[]) public voters;
// Function: make review
function review(uint panelId) public returns (uint) {
// make sure the panelId is right
require(panelId >= 0 && panelId < 4);
// save address to array reviewers
reviewers[panelId] = msg.sender;
return panelId;
}
// Getter for array reviewers
function getReviewers() public view returns (address[4] memory) {
return reviewers;
}
}
|
Getter for array reviewers
|
function getReviewers() public view returns (address[4] memory) {
return reviewers;
}
| 5,415,010 |
./full_match/1/0x4f4fFE6f397F5BC985F4dc1EB5a0eB2D9B93D12D/sources/contracts/V3/LandingPage.sol
|
Allows the contract owner to change the commission percentage for transactions. This function allows the contract owner to adjust the commission percentage within a specified range (5% to 10%). The commission percentage is used to calculate the commission for transactions. Requirements: - The caller must be the contract owner. - The new percentage must be within the valid range (5% to 10%). _newPercentage The new commission percentage to set.
|
function changeCommissionPercentage(
uint256 _newPercentage
) external onlyOwner {
require(
_newPercentage >= 5 && _newPercentage <= 10,
"Out of range: must be 5-10%"
);
uint256 oldPercentage = commissionPercentage;
commissionPercentage = _newPercentage;
emit CommissionPercentageChanged(oldPercentage, commissionPercentage);
}
| 3,146,066 |
./full_match/1/0xF2fd4F08dE4bEc75c5A23bD36FBeef54A3FF182A/sources/Users/enamakel/Work/mahadao/arthcoin/arthcoin-v2/contracts/treasury/TreasuryHelpers.sol
|
Helper function to allocate seigniorage to bond token holders. Seigniorage before the boardrooms get paid./ update accumulated seigniorage
|
function _allocateToBondHolers(uint256 seigniorage)
internal
returns (uint256)
{
uint256 treasuryReserve =
Math.min(
seigniorage,
ICustomERC20(bond).totalSupply().sub(accumulatedSeigniorage)
);
if (treasuryReserve > 0) {
accumulatedSeigniorage = accumulatedSeigniorage.add(
treasuryReserve
);
emit TreasuryFunded(now, treasuryReserve);
return treasuryReserve;
}
return 0;
}
| 8,398,711 |
./full_match/4/0x2db1bD6ffe25FC2321951B0e86300ebA0A685EE0/sources/MMACombat.sol
|
Split the contract balance into halves
|
function swapAndLiquify(uint256 tokens) private lockTheSwap{
uint256 tokensToAddLiquidityWith = tokens / 2;
uint256 toSwap = tokens - tokensToAddLiquidityWith;
uint256 initialBalance = address(this).balance;
swapTokensForETH(toSwap);
uint256 ETHToAddLiquidityWith = address(this).balance - initialBalance;
if(ETHToAddLiquidityWith > 0){
addLiquidity(tokensToAddLiquidityWith, ETHToAddLiquidityWith);
}
}
| 707,482 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.2;
import "./HedgerParty.sol";
import "./SafeMath.sol";
contract OpenHedge1200
{
// OpenHedgeProtocol Version
string public constant OpenHedgeProtocol = "0.12.0";
enum HedgeStatus {AVAILABLE, RESERVED, FUNDED, CANCELLED, ACTIVE, FINISHED}
HedgeStatus public status = HedgeStatus.AVAILABLE;
// Owner address
address private ownerAddr;
// Timestamp contract deployed On
uint256 private deployedOn;
// Seller (Party A) Object
HedgerParty private seller;
// Buyer (Party B) Object
HedgerParty private buyer;
// Maturity of contract in seconds
int256 public maturity;
// Premium/Fee paid to Buyer
uint16 private premium;
// Premium/Fee amount
uint256 private premiumAmount;
// Timestamp this contract became reserved for Party A
uint256 private reservedOn;
// Timestamp contract HedgeStatus is ACTIVE
uint256 private activatedOn;
// Timestamp contract HedgeStatus is FINISHED
uint256 private finishedOn;
event Spend(address asset, address payee, uint256 amount);
// For certain methods that are only callable by ProSwap owner address
modifier onlyOwner {
if (msg.sender != ownerAddr) {
revert("Can only be called by Owner address");
}
_;
}
// For certain methods that are only callable by Seller address
modifier onlySeller {
if (msg.sender != seller.account()) {
revert("Can only be called by Seller address");
}
_;
}
modifier onlyOwnerOrSeller {
if (msg.sender != ownerAddr) {
if (msg.sender != seller.account()) {
revert("Can only be called by Admin or Seller address");
}
}
_;
}
// Todo: add ownership transfer
// Open Hedger Constructor
constructor() {
ownerAddr = msg.sender;
deployedOn = block.timestamp;
seller = new HedgerParty(address(this));
buyer = new HedgerParty(address(this));
}
// Get owner address
function ownerAddress() public view returns (address) {
return (ownerAddr);
}
// Determines if OH-SC can be reset at current stage
function canReset() public view returns (bool) {
if (status == HedgeStatus.RESERVED) {// Available SC was allotted but not yet funded
return true;
}
if (status == HedgeStatus.CANCELLED) {// SC was allotted, funded and then later cancelled
return true;
}
if (status == HedgeStatus.FINISHED) {// SC was finished successfully
return true;
}
return false;
}
// Super reset
function reset() public onlyOwner {
if (!canReset()) {
revert("Hedger cannot be reset");
}
status = HedgeStatus.AVAILABLE;
seller.reset();
buyer.reset();
maturity = 0;
premium = 0;
premiumAmount = 0;
reservedOn = 0;
activatedOn = 0;
finishedOn = 0;
uint256 eth = address(this).balance;
if (eth > 0) {
spend(address(0), ownerAddr, eth);
}
}
// Reserve this AVAILABLE hedge contract
function reserve(address _userA, address _assetA, uint256 _assetAAmount, address _assetB, uint256 _assetBAmount, int256 _maturity, uint16 _premium) public onlyOwner {
if (status != HedgeStatus.AVAILABLE) {
revert("HedgerStatus is not AVAILABLE");
}
status = HedgeStatus.RESERVED;
seller.reserve(_assetA, _assetAAmount);
seller.setUserAccount(_userA);
buyer.reserve(_assetB, _assetBAmount);
maturity = _maturity;
premium = _premium;
premiumAmount = SafeMath.div(SafeMath.mul(premium, _assetAAmount), 10000);
reservedOn = block.timestamp;
}
// Get the premium amount
function getPremium() public view returns (uint16, uint256) {
return (
premium,
premiumAmount
);
}
// Get current timestamp as per last block
function currentTs() public view returns (int256) {
return int256(block.timestamp);
}
// Get number of seconds since contract is HedgeStatus.ACTIVE
function activatedSince() public view returns (int256) {
if (activatedOn > 0) {
return int256(block.timestamp) - int256(activatedOn);
}
return 0;
}
// Check if contract has matured
function isMatured() public view returns (bool) {
if (maturity > 0) {
int256 matured = int256(activatedSince()) - int256(maturity);
if (matured > 0) {
return true;
}
}
return false;
}
// Check if funds are claimable
function isClaimable() public view returns (bool) {
return status == HedgeStatus.ACTIVE && isMatured();
}
// Get seller information
function getPartyA() public view returns (uint8, string memory, address, uint256, address, string memory, uint8, uint256) {
return (
uint8(seller.status()),
seller.getStatusStr(),
seller.account(),
seller.getBalance(),
seller.assetAddr(),
seller.assetCode(),
seller.assetScale(),
seller.amount()
);
}
// Get buyer information
function getPartyB() public view returns (uint8, string memory, address, uint256, address, string memory, uint8, uint256) {
return (
uint8(buyer.status()),
buyer.getStatusStr(),
buyer.account(),
buyer.getBalance(),
buyer.assetAddr(),
buyer.assetCode(),
buyer.assetScale(),
buyer.amount()
);
}
// Spend ETH or ERC20 to payee
function spend(address _asset, address _payee, uint256 _amount) internal {
emit Spend(_asset, _payee, _amount);
if (_asset == address(0)) {
(bool success,) = _payee.call{value : _amount}("");
require(success);
} else {
ERC20(_asset).transfer(_payee, _amount);
}
}
// Checks if hedge can be funded
function canBeFunded() public view {
if (status != HedgeStatus.RESERVED) {
revert("Hedge status cannot be funded");
}
if (seller.isFunded()) {
revert("Hedge already marked funded");
}
}
// Mark hedge as funded
function _markAsFunded() internal {
status = HedgeStatus.FUNDED;
seller.markAsFunded();
}
// Handling incoming ETH
receive() external payable {
// Check if can be funded
canBeFunded();
// Further checks
if (msg.sender != seller.account()) {
revert("Only seller can fund contract with ETH");
}
if (seller.assetAddr() != address(0)) {
revert("Cannot fund contract with ETH");
}
uint256 amtReq = SafeMath.add(seller.amount(), premiumAmount);
uint256 ethBalance = address(this).balance;
if (ethBalance >= amtReq) {
uint256 leftover = ethBalance - amtReq;
if (leftover > 0) {
spend(address(0), seller.account(), leftover);
}
_markAsFunded();
}
}
// Fund the hedge with ERC20
function fundErc20() public onlyOwnerOrSeller returns (bool) {
// Check if can be funded
canBeFunded();
if (seller.assetAddr() == address(0)) {// Selling ERC20?
revert("Cannot fund contract with ERC20");
}
if (seller.account() == address(0)) {
revert("Seller account not set");
}
uint256 amtReq = SafeMath.add(seller.amount(), premiumAmount);
ERC20 sellerToken = ERC20(seller.assetAddr());
// Check ERC20 allowance
(uint256 allowance) = sellerToken.allowance(seller.account(), address(this));
if (allowance < amtReq) {
revert("Not enough ERC20 allowance");
}
(uint balance) = sellerToken.balanceOf(seller.account());
if (balance < amtReq) {
revert("Not enough ERC20 balance");
}
sellerToken.transferFrom(seller.account(), address(this), amtReq);
// Verify transfer from ERC20
(uint newTokenBalance) = sellerToken.balanceOf(address(this));
if (newTokenBalance < amtReq) {
revert("Not receive full ERC20");
}
_markAsFunded();
return true;
}
// Cancel funded, but unsold hedge back to seller's address
function cancel() public onlyOwnerOrSeller {
if (status != HedgeStatus.FUNDED || !seller.isFunded()) {
revert("Cannot cancel hedge at current stage");
}
// Send back all held assets to seller
uint256 balance = seller.getBalance();
spend(seller.assetAddr(), seller.account(), balance);
// Set status to cancelled
status = HedgeStatus.CANCELLED;
seller.markWithdrawn();
}
// Buy the hedge
function buyHedge(address _user) public onlyOwner {
if (buyer.account() != address(0) || buyer.isFunded()) {// Checking if its still up for sale
revert("Hedge no longer available");
}
if (status != HedgeStatus.FUNDED || !seller.isFunded()) {
revert("Cannot buy unfunded hedge");
}
// Check ERC20 allowance
ERC20 token = ERC20(buyer.assetAddr());
(uint256 allowance) = token.allowance(_user, address(this));
if (allowance < buyer.amount()) {
revert("Not enough ERC20 allowance");
}
(uint balance) = token.balanceOf(_user);
if (balance < buyer.amount()) {
revert("Not enough ERC20 balance");
}
// Transfer ERC20 units to itself
token.transferFrom(_user, address(this), buyer.amount());
// Verify transfer from ERC20
(uint ownTokenBalance) = token.balanceOf(address(this));
if (ownTokenBalance < buyer.amount()) {
revert("Not receive full ERC20");
}
// Mark Buyer Hedge Object
buyer.setUserAccount(_user);
buyer.markAsFunded();
// Transfer premium to Buyer
spend(seller.assetAddr(), _user, premiumAmount);
// Activate Hedge
status = HedgeStatus.ACTIVE;
activatedOn = block.timestamp;
}
// Claim hedge
function claim(uint8 _for, uint8 _asset) public returns (bool) {
if (status != HedgeStatus.ACTIVE) {// Status check
revert("Hedge cannot be claimed at this stage");
}
if (maturity > activatedSince()) {// Check maturity
revert("Hedge not matured");
}
if (msg.sender != ownerAddr) {
if (msg.sender == seller.account()) {
_for = 1;
} else if (msg.sender == buyer.account()) {
_for = 2;
} else {
revert("Unauthorized address");
}
}
// Accounting
bool claimed = false;
if (_for == 1) {// On behalf of Party A
if (_asset != 1 && _asset != 2) {// Check asset claim
revert("Invalid seller asset claim");
}
if (_asset == 1) {
// Return asset A to seller
spend(seller.assetAddr(), seller.account(), seller.amount());
// Return asset B to buyer
spend(buyer.assetAddr(), buyer.account(), buyer.amount());
} else if (_asset == 2) {
// Return asset B to seller
spend(buyer.assetAddr(), seller.account(), buyer.amount());
// Return asset A to buyer
spend(seller.assetAddr(), buyer.account(), seller.amount());
}
} else if (_for == 2) {// On behalf of Party B
// Return asset A to seller
spend(seller.assetAddr(), seller.account(), seller.amount());
// Return asset B to buyer
spend(buyer.assetAddr(), buyer.account(), buyer.amount());
} else {
revert("Invalid argument _for");
}
// Change Statuses
status = HedgeStatus.FINISHED;
finishedOn = block.timestamp;
seller.markWithdrawn();
buyer.markWithdrawn();
return claimed;
}
// Refuse any incoming ETH value with calls
fallback() external payable {
revert("Do not send ETH with your call");
}
}
|
Check if funds are claimable
|
function isClaimable() public view returns (bool) {
return status == HedgeStatus.ACTIVE && isMatured();
}
| 1,085,519 |
./full_match/1/0xFd3171eCA94a00e40b3671803d899d3FD86c073c/sources/contracts/PerpetualTranche.sol
|
Counts the number of tokens currently in the reserve.
|
function _reserveCount() private view returns (uint256) {
return _reserves.length();
}
| 2,949,481 |
./partial_match/56/0x83D7Fab5D46371D9F89FbA596f8051dF7A3A5D0a/sources/ScarlettProtocol.sol
|
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 {SCAR-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, "SCAR: decreased allowance below zero"));
return true;
}
| 11,173,017 |
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) {
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".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SKYFChain Tokens
* @dev SKYFChain Token, ERC20 implementation, contract based on Zeppelin contracts:
* Ownable, BasicToken, StandardToken, ERC20Basic, Burnable
*/
contract SKYFToken is Ownable {
using SafeMath for uint256;
enum State {Active, Finalized}
State public state = State.Active;
/**
* @dev ERC20 descriptor variables
*/
string public constant name = "SKYFchain";
string public constant symbol = "SKYFT";
uint8 public decimals = 18;
uint256 public constant startTime = 1534334400;
uint256 public constant airdropTime = startTime + 365 days;
uint256 public constant shortAirdropTime = startTime + 182 days;
uint256 public totalSupply_ = 1200 * 10 ** 24;
uint256 public constant crowdsaleSupply = 528 * 10 ** 24;
uint256 public constant networkDevelopmentSupply = 180 * 10 ** 24;
uint256 public constant communityDevelopmentSupply = 120 * 10 ** 24;
uint256 public constant reserveSupply = 114 * 10 ** 24;
uint256 public constant bountySupply = 18 * 10 ** 24;
uint256 public constant teamSupply = 240 * 10 ** 24;
address public crowdsaleWallet;
address public networkDevelopmentWallet;
address public communityDevelopmentWallet;
address public reserveWallet;
address public bountyWallet;
address public teamWallet;
address public siteAccount;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) balances;
mapping (address => uint256) airdrop;
mapping (address => uint256) shortenedAirdrop;
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 Airdrop(address indexed beneficiary, uint256 amount);
/**
* @dev Contract constructor
*/
constructor(address _crowdsaleWallet
, address _networkDevelopmentWallet
, address _communityDevelopmentWallet
, address _reserveWallet
, address _bountyWallet
, address _teamWallet
, address _siteAccount) public {
require(_crowdsaleWallet != address(0));
require(_networkDevelopmentWallet != address(0));
require(_communityDevelopmentWallet != address(0));
require(_reserveWallet != address(0));
require(_bountyWallet != address(0));
require(_teamWallet != address(0));
require(_siteAccount != address(0));
crowdsaleWallet = _crowdsaleWallet;
networkDevelopmentWallet = _networkDevelopmentWallet;
communityDevelopmentWallet = _communityDevelopmentWallet;
reserveWallet = _reserveWallet;
bountyWallet = _bountyWallet;
teamWallet = _teamWallet;
siteAccount = _siteAccount;
// Issue 528 millions crowdsale tokens
_issueTokens(crowdsaleWallet, crowdsaleSupply);
// Issue 180 millions network development tokens
_issueTokens(networkDevelopmentWallet, networkDevelopmentSupply);
// Issue 120 millions community development tokens
_issueTokens(communityDevelopmentWallet, communityDevelopmentSupply);
// Issue 114 millions reserve tokens
_issueTokens(reserveWallet, reserveSupply);
// Issue 18 millions bounty tokens
_issueTokens(bountyWallet, bountySupply);
// Issue 240 millions team tokens
_issueTokens(teamWallet, teamSupply);
allowed[crowdsaleWallet][siteAccount] = crowdsaleSupply;
emit Approval(crowdsaleWallet, siteAccount, crowdsaleSupply);
allowed[crowdsaleWallet][owner] = crowdsaleSupply;
emit Approval(crowdsaleWallet, owner, crowdsaleSupply);
}
function _issueTokens(address _to, uint256 _amount) internal {
require(balances[_to] == 0);
balances[_to] = balances[_to].add(_amount);
emit Transfer(address(0), _to, _amount);
}
function _airdropUnlocked(address _who) internal view returns (bool) {
return now > airdropTime
|| (now > shortAirdropTime && airdrop[_who] == 0)
|| !isAirdrop(_who);
}
modifier erc20Allowed() {
require(state == State.Finalized || msg.sender == owner|| msg.sender == siteAccount || msg.sender == crowdsaleWallet);
require (_airdropUnlocked(msg.sender));
_;
}
modifier onlyOwnerOrSiteAccount() {
require(msg.sender == owner || msg.sender == siteAccount);
_;
}
function setSiteAccountAddress(address _address) public onlyOwner {
require(_address != address(0));
uint256 allowance = allowed[crowdsaleWallet][siteAccount];
allowed[crowdsaleWallet][siteAccount] = 0;
emit Approval(crowdsaleWallet, siteAccount, 0);
allowed[crowdsaleWallet][_address] = allowed[crowdsaleWallet][_address].add(allowance);
emit Approval(crowdsaleWallet, _address, allowed[crowdsaleWallet][_address]);
siteAccount = _address;
}
/**
* @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];
}
/**
* @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 erc20Allowed returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(_airdropUnlocked(_to));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit 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) public erc20Allowed returns (bool) {
return _transferFrom(msg.sender, _from, _to, _value);
}
function _transferFrom(address _who, address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_airdropUnlocked(_to) || _from == crowdsaleWallet);
uint256 _allowance = allowed[_from][_who];
require(_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][_who] = _allowance.sub(_value);
_recalculateAirdrop(_to);
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 erc20Allowed 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 erc20Allowed 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 erc20Allowed 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;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public erc20Allowed {
_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);
}
function finalize() public onlyOwner {
require(state == State.Active);
require(now > startTime);
state = State.Finalized;
uint256 crowdsaleBalance = balanceOf(crowdsaleWallet);
uint256 burnAmount = networkDevelopmentSupply.mul(crowdsaleBalance).div(crowdsaleSupply);
_burn(networkDevelopmentWallet, burnAmount);
burnAmount = communityDevelopmentSupply.mul(crowdsaleBalance).div(crowdsaleSupply);
_burn(communityDevelopmentWallet, burnAmount);
burnAmount = reserveSupply.mul(crowdsaleBalance).div(crowdsaleSupply);
_burn(reserveWallet, burnAmount);
burnAmount = bountySupply.mul(crowdsaleBalance).div(crowdsaleSupply);
_burn(bountyWallet, burnAmount);
burnAmount = teamSupply.mul(crowdsaleBalance).div(crowdsaleSupply);
_burn(teamWallet, burnAmount);
_burn(crowdsaleWallet, crowdsaleBalance);
}
function addAirdrop(address _beneficiary, uint256 _amount) public onlyOwnerOrSiteAccount {
require(_beneficiary != crowdsaleWallet);
require(_beneficiary != networkDevelopmentWallet);
require(_beneficiary != communityDevelopmentWallet);
require(_beneficiary != bountyWallet);
require(_beneficiary != siteAccount);
//Don't allow to block already bought tokens with airdrop.
require(balances[_beneficiary] == 0 || isAirdrop(_beneficiary));
if (shortenedAirdrop[_beneficiary] != 0) {
shortenedAirdrop[_beneficiary] = shortenedAirdrop[_beneficiary].add(_amount);
}
else {
airdrop[_beneficiary] = airdrop[_beneficiary].add(_amount);
}
_transferFrom(msg.sender, crowdsaleWallet, _beneficiary, _amount);
emit Airdrop(_beneficiary, _amount);
}
function isAirdrop(address _who) public view returns (bool result) {
return airdrop[_who] > 0 || shortenedAirdrop[_who] > 0;
}
function _recalculateAirdrop(address _who) internal {
if(state == State.Active && isAirdrop(_who)) {
uint256 initialAmount = airdrop[_who];
if (initialAmount > 0) {
uint256 rate = balances[_who].div(initialAmount);
if (rate >= 4) {
delete airdrop[_who];
} else if (rate >= 2) {
delete airdrop[_who];
shortenedAirdrop[_who] = initialAmount;
}
} else {
initialAmount = shortenedAirdrop[_who];
if (initialAmount > 0) {
rate = balances[_who].div(initialAmount);
if (rate >= 4) {
delete shortenedAirdrop[_who];
}
}
}
}
}
}
|
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
|
function transfer(address _to, uint256 _value) public erc20Allowed returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(_airdropUnlocked(_to));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 5,858,366 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../interfaces/autofarm/IAutoBTC.sol";
import "../interfaces/autofarm/IAutoFarm.sol";
import "../interfaces/autofarm/IStrat.sol";
/**
* @dev Tokenization V2 of AutoFarm's BTCB position.
*
* AutoFarm is currently the biggest yield farming aggregator in BSC, but it's
* yield position is not tokenized so that AutoFarm users cannot enhance capital
* efficiency of their positions.
*
* The purpose of AutoBTC is to tokenized AutoFarm's BTCB position so that:
* 1. The total supply of autoBTC equals the total shares owned by autoBTC in the BTCB strategy;
* 2. User's autoBTC balance equals the share they could get by depositing the same
* amount of BTCB into AutoFarm directly;
* 3. Users won't lose any AUTO rewards by minting autoBTC.
*
* The interface of autoBTC and autoBTCv2 is unchanged. Only the strategy address and PID are changed.
*/
contract AutoBTCv2 is ERC20Upgradeable, IAutoBTC {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
event Minted(address indexed account, uint256 amount, uint256 mintAmount);
event Redeemed(address indexed account, uint256 amount, uint256 redeemAmount);
event Claimed(address indexed account, uint256 amount);
address public constant BTCB = address(0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c);
address public constant AUTOv2 = address(0xa184088a740c695E156F91f5cC086a06bb78b827);
address public constant AUTOFARM = address(0x0895196562C7868C5Be92459FaE7f877ED450452);
// Only strategy and PID are changed in autoBTCv2
address public constant BTBC_STRAT = address(0xA8c50e9F552886612109fE27CB94111A2F8006DE);
uint256 public constant PID = 0x59;
uint256 public constant WAD = 10**18;
// Accumulated AUTO per token in WAD
uint256 public rewardPerTokenStored;
// Auto balance of this contract in the last update
uint256 public lastReward;
// User address => Reward debt per token for this user
mapping(address => uint256) public rewardPerTokenPaid;
// User address => Claimable rewards for this user
mapping(address => uint256) public rewards;
/**
* @dev Initializes the autoBTC.
*/
function initialize() public initializer {
// BTCB and AutoFarm BTCB share are both 18 decimals.
__ERC20_init("AutoFarm BTC v2", "autoBTCv2");
// We set infinite allowance since autoBTC does not hold any asset.
IERC20Upgradeable(BTCB).safeApprove(AUTOFARM, uint256(int256(-1)));
}
/**
* @dev Returns the current exchange rate between AutoBTC and BTCB.
*/
function exchangeRate() public view override returns (uint256) {
return totalSupply() == 0 ? WAD : IAutoFarm(AUTOFARM).stakedWantTokens(PID, address(this)).mul(WAD).div(totalSupply());
}
/**
* @dev Updates rewards for the user.
*/
function _updateReward(address _account) internal {
uint256 _totalSupply = totalSupply();
uint256 _reward = IERC20Upgradeable(AUTOv2).balanceOf(address(this));
uint256 _rewardDiff = _reward.sub(lastReward);
if (_totalSupply > 0 && _rewardDiff > 0) {
lastReward = _reward;
rewardPerTokenStored = _rewardDiff.mul(WAD).div(_totalSupply).add(rewardPerTokenStored);
}
rewards[_account] = rewardPerTokenStored.sub(rewardPerTokenPaid[_account])
.mul(balanceOf(_account)).div(WAD).add(rewards[_account]);
rewardPerTokenPaid[_account] = rewardPerTokenStored;
}
/**
* @dev Mints autoBTC with BTCB.
* @param _amount Amount of BTCB used to mint autoBTC.
*/
function mint(uint256 _amount) public override {
uint256 _before = IStrat(BTBC_STRAT).sharesTotal();
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
// Note: AutoFarm has an entrance fee
// Each deposit and withdraw trigger AUTO distribution in AutoFarm
IAutoFarm(AUTOFARM).deposit(PID, _amount);
uint256 _after = IStrat(BTBC_STRAT).sharesTotal();
// Updates the rewards before minting
_updateReward(msg.sender);
// 1 autoBTC = 1 share in AutoFarm BTCB strategy
_mint(msg.sender, _after.sub(_before));
emit Minted(msg.sender, _amount, _after.sub(_before));
}
/**
* @dev Redeems autoBTC to BTCB.
* @param _amount Amount of autoBTC to redeem.
*/
function redeem(uint256 _amount) public override {
uint256 _btcbTotal = IStrat(BTBC_STRAT).wantLockedTotal();
uint256 _shareTotal = IStrat(BTBC_STRAT).sharesTotal();
uint256 _btcb = _amount.mul(_btcbTotal).div(_shareTotal);
// Each deposit and withdraw trigger AUTO distribution in AutoFarm
IAutoFarm(AUTOFARM).withdraw(PID, _btcb);
// Updates the rewards before redeeming
_updateReward(msg.sender);
// 1 autoBTC = 1 share in AutoFarm BTCB strategy
_burn(msg.sender, _amount);
_btcb = IERC20Upgradeable(BTCB).balanceOf(address(this));
IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb);
emit Redeemed(msg.sender, _btcb, _amount);
}
/**
* @dev Returns the pending AUTO to the account.
*/
function pendingReward(address _account) public view override returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply == 0) return 0;
uint256 _pendingReward = IAutoFarm(AUTOFARM).pendingAUTO(PID, address(this));
uint256 _rewardPerToken = _pendingReward.mul(WAD).div(_totalSupply).add(rewardPerTokenStored);
return _rewardPerToken.sub(rewardPerTokenPaid[_account]).mul(balanceOf(_account)).div(WAD)
.add(rewards[_account]);
}
/**
* @dev Claims all AUTO available for the caller.
*/
function claimRewards() public override {
// Triggers AUTO distribution with a zero deposit
IAutoFarm(AUTOFARM).deposit(PID, 0);
// Updates the rewards before redeeming
_updateReward(msg.sender);
uint256 _reward = rewards[msg.sender];
if (_reward > 0) {
IERC20Upgradeable(AUTOv2).safeTransfer(msg.sender, _reward);
rewards[msg.sender] = 0;
}
// Need to update the reward balance again!
lastReward = IERC20Upgradeable(AUTOv2).balanceOf(address(this));
emit Claimed(msg.sender, _reward);
}
/**
* @dev Updates AUTO rewards before actual transfer.
*/
function _transfer(address _from, address _to, uint256 _amount) internal virtual override {
// Triggers AUTO distribution with a zero deposit
IAutoFarm(AUTOFARM).deposit(PID, 0);
// Updates the rewards before the actual transfer
_updateReward(_from);
_updateReward(_to);
super._transfer(_from, _to, _amount);
}
}
|
Mints autoBTC with BTCB. _amount Amount of BTCB used to mint autoBTC./ Note: AutoFarm has an entrance fee Each deposit and withdraw trigger AUTO distribution in AutoFarm Updates the rewards before minting 1 autoBTC = 1 share in AutoFarm BTCB strategy
|
function mint(uint256 _amount) public override {
uint256 _before = IStrat(BTBC_STRAT).sharesTotal();
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IAutoFarm(AUTOFARM).deposit(PID, _amount);
uint256 _after = IStrat(BTBC_STRAT).sharesTotal();
_updateReward(msg.sender);
_mint(msg.sender, _after.sub(_before));
emit Minted(msg.sender, _amount, _after.sub(_before));
}
| 6,452,609 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../ConverterVersion.sol";
import "../../interfaces/IConverter.sol";
import "../../interfaces/IConverterAnchor.sol";
import "../../interfaces/IConverterUpgrader.sol";
import "../../../utility/MathEx.sol";
import "../../../utility/ContractRegistryClient.sol";
import "../../../utility/ReentrancyGuard.sol";
import "../../../utility/Time.sol";
import "../../../token/interfaces/IDSToken.sol";
import "../../../token/ReserveToken.sol";
import "../../../INetworkSettings.sol";
/**
* @dev This contract is a specialized version of the converter, which is
* optimized for a liquidity pool that has 2 reserves with 50%/50% weights.
*/
contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time {
using SafeMath for uint256;
using ReserveToken for IReserveToken;
using SafeERC20 for IERC20;
using MathEx for *;
uint256 private constant MAX_UINT128 = 2**128 - 1;
uint256 private constant MAX_UINT112 = 2**112 - 1;
uint256 private constant MAX_UINT32 = 2**32 - 1;
uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes;
uint256 private __reserveBalances;
uint256 private _reserveBalancesProduct;
IReserveToken[] private __reserveTokens;
mapping(IReserveToken => uint256) private __reserveIds;
IConverterAnchor public override anchor; // converter anchor contract
uint32 public override maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000
uint32 public override conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee
// average rate details:
// bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1
// bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1
// bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1
// where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1
uint256 public averageRateInfo;
/**
* @dev triggered after liquidity is added
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityAdded(
address indexed _provider,
IReserveToken indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev triggered after liquidity is removed
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityRemoved(
address indexed _provider,
IReserveToken indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev initializes a new StandardPoolConverter instance
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) public ContractRegistryClient(_registry) validAddress(address(_anchor)) validConversionFee(_maxConversionFee) {
anchor = _anchor;
maxConversionFee = _maxConversionFee;
}
// ensures that the converter is active
modifier active() {
_active();
_;
}
// error message binary size optimization
function _active() internal view {
require(isActive(), "ERR_INACTIVE");
}
// ensures that the converter is not active
modifier inactive() {
_inactive();
_;
}
// error message binary size optimization
function _inactive() internal view {
require(!isActive(), "ERR_ACTIVE");
}
// validates a reserve token address - verifies that the address belongs to one of the reserve tokens
modifier validReserve(IReserveToken _address) {
_validReserve(_address);
_;
}
// error message binary size optimization
function _validReserve(IReserveToken _address) internal view {
require(__reserveIds[_address] != 0, "ERR_INVALID_RESERVE");
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
_validConversionFee(_conversionFee);
_;
}
// error message binary size optimization
function _validConversionFee(uint32 _conversionFee) internal pure {
require(_conversionFee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
}
// validates reserve weight
modifier validReserveWeight(uint32 _weight) {
_validReserveWeight(_weight);
_;
}
// error message binary size optimization
function _validReserveWeight(uint32 _weight) internal pure {
require(_weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT");
}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public pure virtual override returns (uint16) {
return 3;
}
/**
* @dev deposits ether
* can only be called if the converter has an ETH reserve
*/
receive() external payable override(IConverter) validReserve(IReserveToken(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {}
/**
* @dev checks whether or not the converter version is 28 or higher
*
* @return true, since the converter version is 28 or higher
*/
function isV28OrHigher() public pure returns (bool) {
return true;
}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public view virtual override returns (bool) {
return anchor.owner() == address(this);
}
/**
* @dev transfers the anchor ownership
* the new owner needs to accept the transfer
* can only be called by the converter upgrader while the upgrader is the owner
* note that prior to version 28, you should use 'transferAnchorOwnership' instead
*
* @param _newOwner new token owner
*/
function transferAnchorOwnership(address _newOwner) public override ownerOnly only(CONVERTER_UPGRADER) {
anchor.transferOwnership(_newOwner);
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* most converters are also activated as soon as they accept the anchor ownership
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public virtual override ownerOnly {
// verify the the converter has exactly two reserves
require(reserveTokenCount() == 2, "ERR_INVALID_RESERVE_COUNT");
anchor.acceptOwnership();
syncReserveBalances(0);
emit Activation(converterType(), anchor, true);
}
/**
* @dev updates the current conversion fee
* can only be called by the contract owner
*
* @param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee) public override ownerOnly {
require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
emit ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/**
* @dev transfers reserve balances to a new converter during an upgrade
* can only be called by the converter upgraded which should be set at its owner
*
* @param _newConverter address of the converter to receive the new amount
*/
function transferReservesOnUpgrade(address _newConverter)
external
override
protected
ownerOnly
only(CONVERTER_UPGRADER)
{
uint256 reserveCount = __reserveTokens.length;
for (uint256 i = 0; i < reserveCount; ++i) {
IReserveToken reserveToken = __reserveTokens[i];
reserveToken.safeTransfer(_newConverter, reserveToken.balanceOf(address(this)));
syncReserveBalance(reserveToken);
}
}
/**
* @dev upgrades the converter to the latest version
* can only be called by the owner
* note that the owner needs to call acceptOwnership on the new converter after the upgrade
*/
function upgrade() public ownerOnly {
IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
// trigger de-activation event
emit Activation(converterType(), anchor, false);
transferOwnership(address(converterUpgrader));
converterUpgrader.upgrade(version);
acceptOwnership();
}
/**
* @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic
*/
function onUpgradeComplete() external override protected ownerOnly only(CONVERTER_UPGRADER) {
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev returns the number of reserve tokens
* note that prior to version 17, you should use 'connectorTokenCount' instead
*
* @return number of reserve tokens
*/
function reserveTokenCount() public view returns (uint16) {
return uint16(__reserveTokens.length);
}
/**
* @dev returns the array of reserve tokens
*
* @return array of reserve tokens
*/
function reserveTokens() public view returns (IReserveToken[] memory) {
return __reserveTokens;
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IReserveToken _token, uint32 _weight)
public
virtual
override
ownerOnly
inactive
validExternalAddress(address(_token))
validReserveWeight(_weight)
{
// validate input
require(address(_token) != address(anchor) && __reserveIds[_token] == 0, "ERR_INVALID_RESERVE");
require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
__reserveTokens.push(_token);
__reserveIds[_token] = __reserveTokens.length;
}
/**
* @dev returns the reserve's weight
* added in version 28
*
* @param _reserveToken reserve token contract address
*
* @return reserve weight
*/
function reserveWeight(IReserveToken _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
return PPM_RESOLUTION / 2;
}
/**
* @dev returns the balance of a given reserve token
*
* @param _reserveToken reserve token contract address
*
* @return the balance of the given reserve token
*/
function reserveBalance(IReserveToken _reserveToken) public view override returns (uint256) {
uint256 reserveId = __reserveIds[_reserveToken];
require(reserveId != 0, "ERR_INVALID_RESERVE");
return reserveBalance(reserveId);
}
/**
* @dev returns the balances of both reserve tokens
*
* @return the balances of both reserve tokens
*/
function reserveBalances() public view returns (uint256, uint256) {
return reserveBalances(1, 2);
}
/**
* @dev syncs all stored reserve balances
*/
function syncReserveBalances() external {
syncReserveBalances(0);
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*/
function processNetworkFees() external protected {
(uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*
* @param _value amount of ether to exclude from the ether reserve balance (if relevant)
*
* @return new reserve balances
*/
function processNetworkFees(uint256 _value) internal returns (uint256, uint256) {
syncReserveBalances(_value);
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
(ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
reserveBalance0 -= fee0;
reserveBalance1 -= fee1;
setReserveBalances(1, 2, reserveBalance0, reserveBalance1);
__reserveTokens[0].safeTransfer(address(wallet), fee0);
__reserveTokens[1].safeTransfer(address(wallet), fee1);
return (reserveBalance0, reserveBalance1);
}
/**
* @dev returns the reserve balances of the given reserve tokens minus their corresponding fees
*
* @param _reserveTokens reserve tokens
*
* @return reserve balances minus their corresponding fees
*/
function baseReserveBalances(IReserveToken[] memory _reserveTokens) internal view returns (uint256[2] memory) {
uint256 reserveId0 = __reserveIds[_reserveTokens[0]];
uint256 reserveId1 = __reserveIds[_reserveTokens[1]];
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1);
(, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
return [reserveBalance0 - fee0, reserveBalance1 - fee1];
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source reserve token
* @param _targetToken target reserve token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function convert(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) public payable override protected only(BANCOR_NETWORK) returns (uint256) {
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary);
}
/**
* @dev returns the conversion fee for a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFee(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee) / PPM_RESOLUTION;
}
/**
* @dev returns the conversion fee taken from a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFeeInv(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee).div(PPM_RESOLUTION - conversionFee);
}
/**
* @dev loads the stored reserve balance for a given reserve id
*
* @param _reserveId reserve id
*/
function reserveBalance(uint256 _reserveId) internal view returns (uint256) {
return decodeReserveBalance(__reserveBalances, _reserveId);
}
/**
* @dev loads the stored reserve balances
*
* @param _sourceId source reserve id
* @param _targetId target reserve id
*/
function reserveBalances(uint256 _sourceId, uint256 _targetId) internal view returns (uint256, uint256) {
require((_sourceId == 1 && _targetId == 2) || (_sourceId == 2 && _targetId == 1), "ERR_INVALID_RESERVES");
return decodeReserveBalances(__reserveBalances, _sourceId, _targetId);
}
/**
* @dev stores the stored reserve balance for a given reserve id
*
* @param _reserveId reserve id
* @param _reserveBalance reserve balance
*/
function setReserveBalance(uint256 _reserveId, uint256 _reserveBalance) internal {
require(_reserveBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
uint256 otherBalance = decodeReserveBalance(__reserveBalances, 3 - _reserveId);
__reserveBalances = encodeReserveBalances(_reserveBalance, _reserveId, otherBalance, 3 - _reserveId);
}
/**
* @dev stores the stored reserve balances
*
* @param _sourceId source reserve id
* @param _targetId target reserve id
* @param _sourceBalance source reserve balance
* @param _targetBalance target reserve balance
*/
function setReserveBalances(
uint256 _sourceId,
uint256 _targetId,
uint256 _sourceBalance,
uint256 _targetBalance
) internal {
require(_sourceBalance <= MAX_UINT128 && _targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
__reserveBalances = encodeReserveBalances(_sourceBalance, _sourceId, _targetBalance, _targetId);
}
/**
* @dev syncs the stored reserve balance for a given reserve with the real reserve balance
*
* @param _reserveToken address of the reserve token
*/
function syncReserveBalance(IReserveToken _reserveToken) internal {
uint256 reserveId = __reserveIds[_reserveToken];
setReserveBalance(reserveId, _reserveToken.balanceOf(address(this)));
}
/**
* @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant)
*
* @param _value amount of ether to exclude from the ether reserve balance (if relevant)
*/
function syncReserveBalances(uint256 _value) internal {
IReserveToken _reserveToken0 = __reserveTokens[0];
IReserveToken _reserveToken1 = __reserveTokens[1];
uint256 balance0 = _reserveToken0.balanceOf(address(this)) - (_reserveToken0.isNativeToken() ? _value : 0);
uint256 balance1 = _reserveToken1.balanceOf(address(this)) - (_reserveToken1.isNativeToken() ? _value : 0);
setReserveBalances(1, 2, balance0, balance1);
}
/**
* @dev helper, dispatches the Conversion event
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _trader address of the caller who executed the conversion
* @param _amount amount purchased/sold (in the source token)
* @param _returnAmount amount returned (in the target token)
*/
function dispatchConversionEvent(
IReserveToken _sourceToken,
IReserveToken _targetToken,
address _trader,
uint256 _amount,
uint256 _returnAmount,
uint256 _feeAmount
) internal {
emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount));
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount
) public view virtual override active returns (uint256, uint256) {
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
return targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceBalance balance in the source reserve token contract
* @param _targetBalance balance in the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IReserveToken, /* _sourceToken */
IReserveToken, /* _targetToken */
uint256 _sourceBalance,
uint256 _targetBalance,
uint256 _amount
) internal view virtual returns (uint256, uint256) {
uint256 amount = crossReserveTargetAmount(_sourceBalance, _targetBalance, _amount);
uint256 fee = calculateFee(amount);
return (amount - fee, fee);
}
/**
* @dev returns the required amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of target reserve tokens desired
*
* @return required amount in units of the source reserve token
* @return expected fee in units of the target reserve token
*/
function sourceAmountAndFee(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount
) public view virtual active returns (uint256, uint256) {
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
uint256 fee = calculateFeeInv(_amount);
uint256 amount = crossReserveSourceAmount(sourceBalance, targetBalance, _amount.add(fee));
return (amount, fee);
}
/**
* @dev converts a specific amount of source tokens to target tokens
*
* @param _sourceToken source reserve token
* @param _targetToken target reserve token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) internal returns (uint256) {
// update the recent average rate
updateRecentAverageRate();
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
// get the target amount minus the conversion fee and the conversion fee
(uint256 amount, uint256 fee) =
targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
// ensure that the trade gives something in return
require(amount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
assert(amount < targetBalance);
// ensure that the input amount was already deposited
uint256 actualSourceBalance = _sourceToken.balanceOf(address(this));
if (_sourceToken.isNativeToken()) {
require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
} else {
require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= _amount, "ERR_INVALID_AMOUNT");
}
// sync the reserve balances
setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - amount);
// transfer funds to the beneficiary in the to reserve token
_targetToken.safeTransfer(_beneficiary, amount);
// dispatch the conversion event
dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
// dispatch rate updates
dispatchTokenRateUpdateEvents(_sourceToken, _targetToken, actualSourceBalance, targetBalance - amount);
return amount;
}
/**
* @dev returns the recent average rate of 1 `_token` in the other reserve token units
*
* @param _token token to get the rate for
*
* @return recent average rate between the reserves (numerator)
* @return recent average rate between the reserves (denominator)
*/
function recentAverageRate(IReserveToken _token) external view validReserve(_token) returns (uint256, uint256) {
// get the recent average rate of reserve 0
uint256 rate = calcRecentAverageRate(averageRateInfo);
uint256 rateN = decodeAverageRateN(rate);
uint256 rateD = decodeAverageRateD(rate);
if (_token == __reserveTokens[0]) {
return (rateN, rateD);
}
return (rateD, rateN);
}
/**
* @dev updates the recent average rate if needed
*/
function updateRecentAverageRate() internal {
uint256 averageRateInfo1 = averageRateInfo;
uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1);
if (averageRateInfo1 != averageRateInfo2) {
averageRateInfo = averageRateInfo2;
}
}
/**
* @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units
*
* @param _averageRateInfo a local copy of the `averageRateInfo` state-variable
*
* @return recent average rate between the reserves
*/
function calcRecentAverageRate(uint256 _averageRateInfo) internal view returns (uint256) {
// get the previous average rate and its update-time
uint256 prevAverageRateT = decodeAverageRateT(_averageRateInfo);
uint256 prevAverageRateN = decodeAverageRateN(_averageRateInfo);
uint256 prevAverageRateD = decodeAverageRateD(_averageRateInfo);
// get the elapsed time since the previous average rate was calculated
uint256 currentTime = time();
uint256 timeElapsed = currentTime - prevAverageRateT;
// if the previous average rate was calculated in the current block, the average rate remains unchanged
if (timeElapsed == 0) {
return _averageRateInfo;
}
// get the current rate between the reserves
(uint256 currentRateD, uint256 currentRateN) = reserveBalances();
// if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate
if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) {
(currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, currentRateN, currentRateD);
}
uint256 x = prevAverageRateD.mul(currentRateN);
uint256 y = prevAverageRateN.mul(currentRateD);
// since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath:
uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed));
uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD);
(newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, newRateN, newRateD);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _minReturn token minimum return-amount
*
* @return amount of pool tokens issued
*/
function addLiquidity(
IReserveToken[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256 _minReturn
) public payable protected active returns (uint256) {
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
// if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
require(
(!_reserveTokens[0].isNativeToken() || _reserveAmounts[0] == msg.value) &&
(!_reserveTokens[1].isNativeToken() || _reserveAmounts[1] == msg.value),
"ERR_ETH_AMOUNT_MISMATCH"
);
// if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
if (msg.value > 0) {
require(__reserveIds[IReserveToken(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)] != 0, "ERR_NO_ETH_RESERVE");
}
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply
uint256 totalSupply = poolToken.totalSupply();
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value);
uint256 amount;
uint256[2] memory reserveAmounts;
// calculate the amount of pool tokens to mint for the caller
// and the amount of reserve tokens to transfer from the caller
if (totalSupply == 0) {
amount = MathEx.geometricMean(_reserveAmounts);
reserveAmounts[0] = _reserveAmounts[0];
reserveAmounts[1] = _reserveAmounts[1];
} else {
(amount, reserveAmounts) = addLiquidityAmounts(
_reserveTokens,
_reserveAmounts,
prevReserveBalances,
totalSupply
);
}
uint256 newPoolTokenSupply = totalSupply.add(amount);
for (uint256 i = 0; i < 2; i++) {
IReserveToken reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
assert(reserveAmount <= _reserveAmounts[i]);
// transfer each one of the reserve amounts from the user to the pool
if (!reserveToken.isNativeToken()) {
// ETH has already been transferred as part of the transaction
reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount);
} else if (_reserveAmounts[i] > reserveAmount) {
// transfer the extra amount of ETH back to the user
reserveToken.safeTransfer(msg.sender, _reserveAmounts[i] - reserveAmount);
}
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount);
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
// verify that the equivalent amount of tokens is equal to or larger than the user's expectation
require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
// issue the tokens to the user
poolToken.issue(msg.sender, amount);
// return the amount of pool tokens issued
return amount;
}
/**
* @dev get the amount of pool tokens to mint for the caller
* and the amount of reserve tokens to transfer from the caller
*
* @param _reserveAmounts amount of each reserve token
* @param _reserveBalances balance of each reserve token
* @param _totalSupply total supply of pool tokens
*
* @return amount of pool tokens to mint for the caller
* @return amount of reserve tokens to transfer from the caller
*/
function addLiquidityAmounts(
IReserveToken[] memory, /* _reserveTokens */
uint256[] memory _reserveAmounts,
uint256[2] memory _reserveBalances,
uint256 _totalSupply
) internal view virtual returns (uint256, uint256[2] memory) {
this;
uint256 index =
_reserveAmounts[0].mul(_reserveBalances[1]) < _reserveAmounts[1].mul(_reserveBalances[0]) ? 0 : 1;
uint256 amount = fundSupplyAmount(_totalSupply, _reserveBalances[index], _reserveAmounts[index]);
uint256[2] memory reserveAmounts =
[fundCost(_totalSupply, _reserveBalances[0], amount), fundCost(_totalSupply, _reserveBalances[1], amount)];
return (amount, reserveAmounts);
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
*
* @param _amount token amount
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
*
* @return the amount of each reserve token granted for the given amount of pool tokens
*/
function removeLiquidity(
uint256 _amount,
IReserveToken[] memory _reserveTokens,
uint256[] memory _reserveMinReturnAmounts
) public protected active returns (uint256[] memory) {
// verify the user input
bool inputRearranged = verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply BEFORE destroying the user tokens
uint256 totalSupply = poolToken.totalSupply();
// destroy the user tokens
poolToken.destroy(msg.sender, _amount);
uint256 newPoolTokenSupply = totalSupply.sub(_amount);
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0);
uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, totalSupply, prevReserveBalances);
for (uint256 i = 0; i < 2; i++) {
IReserveToken reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount);
// transfer each one of the reserve amounts from the pool to the user
reserveToken.safeTransfer(msg.sender, reserveAmount);
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
if (inputRearranged) {
uint256 tempReserveAmount = reserveAmounts[0];
reserveAmounts[0] = reserveAmounts[1];
reserveAmounts[1] = tempReserveAmount;
}
// return the amount of each reserve token granted for the given amount of pool tokens
return reserveAmounts;
}
/**
* @dev given the amount of one of the reserve tokens to add liquidity of,
* returns the required amount of each one of the other reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveTokens address of each reserve token
* @param _reserveTokenIndex index of the relevant reserve token
* @param _reserveAmount amount of the relevant reserve token
*
* @return the required amount of each one of the reserve tokens
*/
function addLiquidityCost(
IReserveToken[] memory _reserveTokens,
uint256 _reserveTokenIndex,
uint256 _reserveAmount
) public view returns (uint256[] memory) {
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
uint256 amount = fundSupplyAmount(totalSupply, baseBalances[_reserveTokenIndex], _reserveAmount);
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], amount);
reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], amount);
return reserveAmounts;
}
/**
* @dev returns the amount of pool tokens entitled for given amounts of reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
*
* @return the amount of pool tokens entitled for the given amounts of reserve tokens
*/
function addLiquidityReturn(IReserveToken[] memory _reserveTokens, uint256[] memory _reserveAmounts)
public
view
returns (uint256)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
(uint256 amount, ) = addLiquidityAmounts(_reserveTokens, _reserveAmounts, baseBalances, totalSupply);
return amount;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _reserveTokens address of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReturn(uint256 _amount, IReserveToken[] memory _reserveTokens)
public
view
returns (uint256[] memory)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
return removeLiquidityReserveAmounts(_amount, totalSupply, baseBalances);
}
/**
* @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
* we take this input in order to allow specifying the corresponding reserve amounts in any order
* this function rearranges the input arrays according to the converter's array of reserve tokens
*
* @param _reserveTokens array of reserve tokens
* @param _reserveAmounts array of reserve amounts
* @param _amount token amount
*
* @return true if the function has rearranged the input arrays; false otherwise
*/
function verifyLiquidityInput(
IReserveToken[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256 _amount
) private view returns (bool) {
require(validReserveAmounts(_reserveAmounts) && _amount > 0, "ERR_ZERO_AMOUNT");
uint256 reserve0Id = __reserveIds[_reserveTokens[0]];
uint256 reserve1Id = __reserveIds[_reserveTokens[1]];
if (reserve0Id == 2 && reserve1Id == 1) {
IReserveToken tempReserveToken = _reserveTokens[0];
_reserveTokens[0] = _reserveTokens[1];
_reserveTokens[1] = tempReserveToken;
uint256 tempReserveAmount = _reserveAmounts[0];
_reserveAmounts[0] = _reserveAmounts[1];
_reserveAmounts[1] = tempReserveAmount;
return true;
}
require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE");
return false;
}
/**
* @dev checks whether or not both reserve amounts are larger than zero
*
* @param _reserveAmounts array of reserve amounts
*
* @return true if both reserve amounts are larger than zero; false otherwise
*/
function validReserveAmounts(uint256[] memory _reserveAmounts) internal pure virtual returns (bool) {
return _reserveAmounts[0] > 0 && _reserveAmounts[1] > 0;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _totalSupply total supply of pool tokens
* @param _reserveBalances balance of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReserveAmounts(
uint256 _amount,
uint256 _totalSupply,
uint256[2] memory _reserveBalances
) private pure returns (uint256[] memory) {
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = liquidateReserveAmount(_totalSupply, _reserveBalances[0], _amount);
reserveAmounts[1] = liquidateReserveAmount(_totalSupply, _reserveBalances[1], _amount);
return reserveAmounts;
}
/**
* @dev dispatches token rate update events for the reserve tokens and the pool token
*
* @param _sourceToken address of the source reserve token
* @param _targetToken address of the target reserve token
* @param _sourceBalance balance of the source reserve token
* @param _targetBalance balance of the target reserve token
*/
function dispatchTokenRateUpdateEvents(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _sourceBalance,
uint256 _targetBalance
) private {
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply of pool tokens
uint256 poolTokenSupply = poolToken.totalSupply();
// dispatch token rate update event for the reserve tokens
emit TokenRateUpdate(address(_sourceToken), address(_targetToken), _targetBalance, _sourceBalance);
// dispatch token rate update events for the pool token
emit TokenRateUpdate(address(poolToken), address(_sourceToken), _sourceBalance, poolTokenSupply);
emit TokenRateUpdate(address(poolToken), address(_targetToken), _targetBalance, poolTokenSupply);
}
function encodeReserveBalance(uint256 _balance, uint256 _id) private pure returns (uint256) {
assert(_balance <= MAX_UINT128 && (_id == 1 || _id == 2));
return _balance << ((_id - 1) * 128);
}
function decodeReserveBalance(uint256 _balances, uint256 _id) private pure returns (uint256) {
assert(_id == 1 || _id == 2);
return (_balances >> ((_id - 1) * 128)) & MAX_UINT128;
}
function encodeReserveBalances(
uint256 _balance0,
uint256 _id0,
uint256 _balance1,
uint256 _id1
) private pure returns (uint256) {
return encodeReserveBalance(_balance0, _id0) | encodeReserveBalance(_balance1, _id1);
}
function decodeReserveBalances(
uint256 _balances,
uint256 _id0,
uint256 _id1
) private pure returns (uint256, uint256) {
return (decodeReserveBalance(_balances, _id0), decodeReserveBalance(_balances, _id1));
}
function encodeAverageRateInfo(
uint256 _averageRateT,
uint256 _averageRateN,
uint256 _averageRateD
) private pure returns (uint256) {
assert(_averageRateT <= MAX_UINT32 && _averageRateN <= MAX_UINT112 && _averageRateD <= MAX_UINT112);
return (_averageRateT << 224) | (_averageRateN << 112) | _averageRateD;
}
function decodeAverageRateT(uint256 _averageRateInfo) private pure returns (uint256) {
return _averageRateInfo >> 224;
}
function decodeAverageRateN(uint256 _averageRateInfo) private pure returns (uint256) {
return (_averageRateInfo >> 112) & MAX_UINT112;
}
function decodeAverageRateD(uint256 _averageRateInfo) private pure returns (uint256) {
return _averageRateInfo & MAX_UINT112;
}
/**
* @dev returns the largest integer smaller than or equal to the square root of a given value
*
* @param x the given value
*
* @return the largest integer smaller than or equal to the square root of the given value
*/
function floorSqrt(uint256 x) private pure returns (uint256) {
return x > 0 ? MathEx.floorSqrt(x) : 0;
}
function crossReserveTargetAmount(
uint256 _sourceReserveBalance,
uint256 _targetReserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount);
}
function crossReserveSourceAmount(
uint256 _sourceReserveBalance,
uint256 _targetReserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_amount < _targetReserveBalance, "ERR_INVALID_AMOUNT");
if (_amount == 0) {
return 0;
}
return (_sourceReserveBalance.mul(_amount) - 1) / (_targetReserveBalance - _amount) + 1;
}
function fundCost(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
}
function fundSupplyAmount(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
return _amount.mul(_supply) / _reserveBalance;
}
function liquidateReserveAmount(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
// special case for liquidating the entire supply
if (_amount == _supply) {
return _reserveBalance;
}
return _amount.mul(_reserveBalance) / _supply;
}
/**
* @dev returns the network wallet and fees
*
* @param reserveBalance0 1st reserve balance
* @param reserveBalance1 2nd reserve balance
*
* @return the network wallet
* @return the network fee on the 1st reserve
* @return the network fee on the 2nd reserve
*/
function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1)
private
view
returns (
ITokenHolder,
uint256,
uint256
)
{
uint256 prevPoint = floorSqrt(_reserveBalancesProduct);
uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1);
if (prevPoint >= currPoint) {
return (ITokenHolder(address(0)), 0, 0);
}
(ITokenHolder networkFeeWallet, uint32 networkFee) =
INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams();
uint256 n = (currPoint - prevPoint) * networkFee;
uint256 d = currPoint * PPM_RESOLUTION;
return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d));
}
/**
* @dev deprecated since version 28, backward compatibility - use only for earlier versions
*/
function token() public view override returns (IConverterAnchor) {
return anchor;
}
/**
* @dev deprecated, backward compatibility
*/
function transferTokenOwnership(address _newOwner) public override ownerOnly {
transferAnchorOwnership(_newOwner);
}
/**
* @dev deprecated, backward compatibility
*/
function acceptTokenOwnership() public override ownerOnly {
acceptAnchorOwnership();
}
/**
* @dev deprecated, backward compatibility
*/
function connectors(IReserveToken _address)
public
view
override
returns (
uint256,
uint32,
bool,
bool,
bool
)
{
uint256 reserveId = __reserveIds[_address];
if (reserveId != 0) {
return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true);
}
return (0, 0, false, false, false);
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokens(uint256 _index) public view override returns (IReserveToken) {
return __reserveTokens[_index];
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokenCount() public view override returns (uint16) {
return reserveTokenCount();
}
/**
* @dev deprecated, backward compatibility
*/
function getConnectorBalance(IReserveToken _connectorToken) public view override returns (uint256) {
return reserveBalance(_connectorToken);
}
/**
* @dev deprecated, backward compatibility
*/
function getReturn(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount
) public view returns (uint256, uint256) {
return targetAmountAndFee(_sourceToken, _targetToken, _amount);
}
}
|
error message binary size optimization
|
function _validReserve(IReserveToken _address) internal view {
require(__reserveIds[_address] != 0, "ERR_INVALID_RESERVE");
}
| 12,984,642 |
//Address: 0x672a1ad4f667fb18a333af13667aa0af1f5b5bdd
//Contract name: CREDToken
//Balance: 0 Ether
//Verification Date: 12/7/2017
//Transacion Count: 13410
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @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 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 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 Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
/**
* @title 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 TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
contract MonthlyTokenVesting is TokenVesting {
uint256 public previousTokenVesting = 0;
function MonthlyTokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
) public
TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable)
{ }
function release(ERC20Basic token) public onlyOwner {
require(now >= previousTokenVesting + 30 days);
super.release(token);
previousTokenVesting = now;
}
}
contract CREDToken is CappedToken {
using SafeMath for uint256;
/**
* Constant fields
*/
string public constant name = "Verify Token";
uint8 public constant decimals = 18;
string public constant symbol = "CRED";
/**
* Immutable state variables
*/
// Time when team and reserved tokens are unlocked
uint256 public reserveUnlockTime;
address public teamWallet;
address public reserveWallet;
address public advisorsWallet;
/**
* State variables
*/
uint256 teamLocked;
uint256 reserveLocked;
uint256 advisorsLocked;
// Are the tokens non-transferrable?
bool public locked = true;
// When tokens can be unfreezed.
uint256 public unfreezeTime = 0;
bool public unlockedReserveAndTeamFunds = false;
MonthlyTokenVesting public advisorsVesting = MonthlyTokenVesting(address(0));
/**
* Events
*/
event MintLocked(address indexed to, uint256 amount);
event Unlocked(address indexed to, uint256 amount);
/**
* Modifiers
*/
// Tokens must not be locked.
modifier whenLiquid {
require(!locked);
_;
}
modifier afterReserveUnlockTime {
require(now >= reserveUnlockTime);
_;
}
modifier unlockReserveAndTeamOnce {
require(!unlockedReserveAndTeamFunds);
_;
}
/**
* Constructor
*/
function CREDToken(
uint256 _cap,
uint256 _yearLockEndTime,
address _teamWallet,
address _reserveWallet,
address _advisorsWallet
)
CappedToken(_cap)
public
{
require(_yearLockEndTime != 0);
require(_teamWallet != address(0));
require(_reserveWallet != address(0));
require(_advisorsWallet != address(0));
reserveUnlockTime = _yearLockEndTime;
teamWallet = _teamWallet;
reserveWallet = _reserveWallet;
advisorsWallet = _advisorsWallet;
}
// Mint a certain number of tokens that are locked up.
// _value has to be bounded not to overflow.
function mintAdvisorsTokens(uint256 _value) public onlyOwner canMint {
require(advisorsLocked == 0);
require(_value.add(totalSupply) <= cap);
advisorsLocked = _value;
MintLocked(advisorsWallet, _value);
}
function mintTeamTokens(uint256 _value) public onlyOwner canMint {
require(teamLocked == 0);
require(_value.add(totalSupply) <= cap);
teamLocked = _value;
MintLocked(teamWallet, _value);
}
function mintReserveTokens(uint256 _value) public onlyOwner canMint {
require(reserveLocked == 0);
require(_value.add(totalSupply) <= cap);
reserveLocked = _value;
MintLocked(reserveWallet, _value);
}
/// Finalise any minting operations. Resets the owner and causes normal tokens
/// to be frozen. Also begins the countdown for locked-up tokens.
function finalise() public onlyOwner {
require(reserveLocked > 0);
require(teamLocked > 0);
require(advisorsLocked > 0);
advisorsVesting = new MonthlyTokenVesting(advisorsWallet, now, 92 days, 2 years, false);
mint(advisorsVesting, advisorsLocked);
finishMinting();
owner = 0;
unfreezeTime = now + 1 weeks;
}
// Causes tokens to be liquid 1 week after the tokensale is completed
function unfreeze() public {
require(unfreezeTime > 0);
require(now >= unfreezeTime);
locked = false;
}
/// Unlock any now freeable tokens that are locked up for team and reserve accounts .
function unlockTeamAndReserveTokens() public whenLiquid afterReserveUnlockTime unlockReserveAndTeamOnce {
require(totalSupply.add(teamLocked).add(reserveLocked) <= cap);
totalSupply = totalSupply.add(teamLocked).add(reserveLocked);
balances[teamWallet] = balances[teamWallet].add(teamLocked);
balances[reserveWallet] = balances[reserveWallet].add(reserveLocked);
teamLocked = 0;
reserveLocked = 0;
unlockedReserveAndTeamFunds = true;
Transfer(address(0), teamWallet, teamLocked);
Transfer(address(0), reserveWallet, reserveLocked);
Unlocked(teamWallet, teamLocked);
Unlocked(reserveWallet, reserveLocked);
}
function unlockAdvisorTokens() public whenLiquid {
advisorsVesting.release(this);
}
/**
* Methods overriding some OpenZeppelin functions to prevent calling them when token is not liquid.
*/
function transfer(address _to, uint256 _value) public whenLiquid returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenLiquid returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenLiquid returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint256 _addedValue) public whenLiquid returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public whenLiquid returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
|
Unlock any now freeable tokens that are locked up for team and reserve accounts .
|
function unlockTeamAndReserveTokens() public whenLiquid afterReserveUnlockTime unlockReserveAndTeamOnce {
require(totalSupply.add(teamLocked).add(reserveLocked) <= cap);
totalSupply = totalSupply.add(teamLocked).add(reserveLocked);
balances[teamWallet] = balances[teamWallet].add(teamLocked);
balances[reserveWallet] = balances[reserveWallet].add(reserveLocked);
teamLocked = 0;
reserveLocked = 0;
unlockedReserveAndTeamFunds = true;
Transfer(address(0), teamWallet, teamLocked);
Transfer(address(0), reserveWallet, reserveLocked);
Unlocked(teamWallet, teamLocked);
Unlocked(reserveWallet, reserveLocked);
}
| 896,680 |
./full_match/1/0xb69E35fB4A157028b92F42655090b984609Ae598/sources/contracts/WrappedCollateralToken.f.sol
|
Returns lowest total debt that will be split. Minimum collateralization ratio for position Splits collateral between protocol and liquidator. totalCollateral Amount of collateral to split. totalDebt Amount of debt to split. price Price of collateral. isRedistribution True if this is a redistribution. return collateralToSendToProtocol Amount of collateral to send to protocol. return collateralToSentToLiquidator Amount of collateral to send to liquidator. Common interface for the Position Manager. --- Types ---
|
interface IPositionManager is IFeeCollector {
function getPriceOracleResponse() external returns (PriceOracleResponse memory);
function timeout() external view returns (uint256);
function TARGET_DIGITS() external view returns (uint256);
function DEVIATION() external view returns (uint256);
}
}
}
}
}
}
struct CollateralTokenInfo {
IERC20Indexable collateralToken;
IERC20Indexable debtToken;
IPriceFeed priceFeed;
ISplitLiquidationCollateral splitLiquidation;
bool isEnabled;
uint256 lastFeeOperationTime;
uint256 borrowingSpread;
uint256 baseRate;
uint256 redemptionSpread;
uint256 redemptionRebate;
}
IERC20 collateralToken,
IERC20Indexable raftCollateralToken,
IERC20Indexable raftDebtToken,
IPriceFeed priceFeed
);
address indexed position, IERC20 indexed collateralToken, uint256 collateralAmount, bool isCollateralIncrease
);
address indexed position, IERC20 indexed collateralToken, uint256 debtAmount, bool isDebtIncrease
);
address indexed liquidator,
address indexed position,
IERC20 indexed collateralToken,
uint256 debtLiquidated,
uint256 collateralLiquidated,
uint256 collateralSentToLiquidator,
uint256 collateralLiquidationFeePaid,
bool isRedistribution
);
IERC20 collateralToken, ISplitLiquidationCollateral indexed newSplitLiquidationCollateral
);
IERC20 collateralToken, uint256 newTotalCollateral, uint256 minimumCollateral
);
event PositionManagerDeployed(IRToken rToken, address feeRecipient);
event CollateralTokenAdded(
event CollateralTokenModified(IERC20 collateralToken, bool isEnabled);
event DelegateWhitelisted(address indexed position, address indexed delegate, bool whitelisted);
event PositionCreated(address indexed position, IERC20 indexed collateralToken);
event PositionClosed(address indexed position);
event CollateralChanged(
event DebtChanged(
event RBorrowingFeePaid(IERC20 collateralToken, address indexed position, uint256 feeAmount);
event Liquidation(
event Redemption(address indexed redeemer, uint256 amount, uint256 collateralSent, uint256 fee, uint256 rebate);
event BorrowingSpreadUpdated(uint256 borrowingSpread);
event RedemptionRebateUpdated(uint256 redemptionRebate);
event RedemptionSpreadUpdated(IERC20 collateralToken, uint256 redemptionSpread);
event BaseRateUpdated(IERC20 collateralToken, uint256 baseRate);
event LastFeeOpTimeUpdated(IERC20 collateralToken, uint256 lastFeeOpTime);
event SplitLiquidationCollateralChanged(
error InvalidMaxFeePercentage();
error MaxFeePercentageOutOfRange();
error AmountIsZero();
error NothingToLiquidate();
error CannotLiquidateLastPosition();
error TotalDebtCannotBeLowerThanMinDebt(IERC20 collateralToken, uint256 newTotalDebt);
error TotalCollateralCannotBeLowerThanMinCollateral(
error FeeEatsUpAllReturnedCollateral();
error BorrowingSpreadExceedsMaximum();
error RedemptionRebateExceedsMaximum();
error RedemptionSpreadOutOfRange();
error NoCollateralOrDebtChange();
error InvalidPosition();
error NewICRLowerThanMCR(uint256 newICR);
error NetDebtBelowMinimum(uint256 netDebt);
error InvalidDelegateAddress();
error DelegateNotWhitelisted();
error FeeExceedsMaxFee(uint256 fee, uint256 amount, uint256 maxFeePercentage);
error PositionCollateralTokenMismatch();
error CollateralTokenAddressCannotBeZero();
error PriceFeedAddressCannotBeZero();
error CollateralTokenAlreadyAdded();
error CollateralTokenNotAdded();
error CollateralTokenDisabled();
error SplitLiquidationCollateralCannotBeZero();
error WrongCollateralParamsForFullRepayment();
}
| 2,974,973 |
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // price to register a name
mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games
mapping(address => bytes32) public gameNames_; // lookup a games name
mapping(address => uint256) public gameIDs_; // lokup a games ID
uint256 public gID_; // total number of games
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyAdmin()
{
require(msg.sender == admin);
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev registers a name. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who refered you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// register name
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev players, if you registered a profile, before a game was released, or
* set the all bool to false when you registered, use this function to push
* your profile to a single game. also, if you've updated your name, you
* can use this to push your name to games of your choosing.
* -functionhash- 0x81c5b206
* @param _gameID game id
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// add players profile and most recent name
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// add list of all names
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev players, use this to push your player profile to all registered games.
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev players use this to change back to one of your old names. tip, you'll
* still need to push that info to existing games.
* -functionhash- 0xb9291296
* @param _nameString the name you want to use
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// filter name, and get pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// make sure they own the name
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// update their current name
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// add name to player profile, registry, and name book
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// registration fee goes directly to community rewards
admin.transfer(address(this).balance);
// push player info to games
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// fire event
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
onlyAdmin()
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
}
function setRegistrationFee(uint256 _fee)
onlyAdmin()
public
{
registrationFee_ = _fee;
}
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
players, if you registered a profile, before a game was released, or set the all bool to false when you registered, use this function to push your profile to a single game. also, if you&39;ve updated your name, you can use this to push your name to games of your choosing. -functionhash- 0x81c5b206 _gameID game id/ add players profile and most recent name add list of all names
|
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
| 2,041,562 |
./full_match/5/0x04f42E2bB2278065ce006E1f1c24cf1939D3bdE3/sources/browser/Update.sol
|
Before it was OnlyOwner, but it is called also inside voteAccordingMajority ( inside waiveDiscrepancies)
|
function winningProposal() internal view returns (uint winningProposal_){
uint winningVoteCount = 0;
for (uint p = 0; p < proposals.length; p++) {
if (proposals[p].voteCount > winningVoteCount) {
winningVoteCount = proposals[p].voteCount;
winningProposal_ = p;
}
}
}
| 1,883,649 |
// Liquidity contract with pegged value
pragma solidity 0.5.16;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
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 token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity 0.5.16;
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity 0.5.16;
contract Context {
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
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity 0.5.16;
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity 0.5.16;
contract Liquidity_v8 is Ownable {
using SafeMath for uint256;
/**
* @dev Structs to store user staking data.
*/
struct Deposits {
uint256 depositAmount;
uint256 depositTime;
uint64 userIndex;
bool paid;
}
/**
* @dev Structs to store interest rate change.
*/
struct Rates {
uint64 newInterestRate;
uint256 timeStamp;
}
mapping(address => bool) private hasStaked;
mapping(address => Deposits) private deposits;
mapping(uint64 => Rates) public rates;
string public name;
address public tokenAddress;
address public rewardTokenAddress;
uint256 public stakedTotal;
uint256 public totalReward;
uint256 public rewardBalance;
uint256 public stakedBalance;
uint64 public rate;
uint64 public index;
IERC20 public ERC20Interface;
/**
* @dev Emitted when user stakes 'stakedAmount' value of tokens
*/
event Staked(
address indexed token,
address indexed staker_,
uint256 stakedAmount_
);
/**
* @dev Emitted when user withdraws his stakings
*/
event PaidOut(
address indexed token,
address indexed rewardToken,
address indexed staker_,
uint256 amount_,
uint256 reward_
);
/**
* @param
* name_ name of the contract
* tokenAddress_ contract address of the token
* rewardTokenAddress_ contract address of the reward token
* rate_ APY rate for Flex contract multiplied by 100
*/
constructor(
string memory name_,
address tokenAddress_,
address rewardTokenAddress_,
uint64 rate_
) public Ownable() {
name = name_;
require(tokenAddress_ != address(0), "Token address: 0 address");
tokenAddress = tokenAddress_;
require(
rewardTokenAddress_ != address(0),
"Reward token address: 0 address"
);
rewardTokenAddress = rewardTokenAddress_;
require(rate_ != 0, "Zero interest rate");
rate = rate_;
rates[index] = Rates(rate, block.timestamp);
}
/**
* @dev to set interest rates
*/
function setRate(uint64 rate_) external onlyOwner {
require(rate_ != 0, "Zero interest rate");
index++;
rates[index] = Rates(rate_, block.timestamp);
rate = rate_;
}
/**
* @dev to add rewards to the staking contract
* once the allowance is given to this contract for 'rewardAmount' by the user
*/
function addReward(uint256 rewardAmount)
external
_hasAllowance(msg.sender, rewardAmount, rewardTokenAddress)
returns (bool)
{
require(rewardAmount > 0, "Reward must be positive");
address from = msg.sender;
if (!_payMe(from, rewardAmount, rewardTokenAddress)) {
return false;
}
totalReward = totalReward.add(rewardAmount);
rewardBalance = rewardBalance.add(rewardAmount);
return true;
}
/**
* @dev returns user staking data
*/
function userDeposits(address user)
external
view
returns (
uint256,
uint256,
uint256,
bool
)
{
if (hasStaked[user]) {
return (
deposits[user].depositAmount,
deposits[user].depositTime,
deposits[user].userIndex,
deposits[user].paid
);
}
}
/**
* Requirements:
* - 'amount' Amount to be staked
/**
* @dev to stake 'amount' value of tokens
* once the user has given allowance to the staking contract
*/
function stake(uint256 amount)
external
_hasAllowance(msg.sender, amount, tokenAddress)
returns (bool)
{
require(amount > 0, "Can't stake 0 amount");
address from = msg.sender;
require(!hasStaked[from], "Already staked");
return _stake(from, amount);
}
function _stake(address staker, uint256 amount) private returns (bool) {
if (!_payMe(staker, amount, tokenAddress)) {
return false;
}
hasStaked[staker] = true;
deposits[staker] = Deposits(amount, block.timestamp, index, false);
emit Staked(tokenAddress, staker, amount);
// Transfer is completed
stakedBalance = stakedBalance.add(amount);
stakedTotal = stakedTotal.add(amount);
return true;
}
/**
* @dev to withdraw user stakings after the lock period ends.
*/
function withdraw() external returns (bool) {
address from = msg.sender;
require(hasStaked[from], "No stakes found for user");
require(!deposits[from].paid, "Already paid out");
return (_withdraw(from));
}
function _withdraw(address from) private returns (bool) {
uint256 getPeggedBNF = getPeggedValue();
uint256 reward = _calculate(from).mul(getPeggedBNF).div(10**18);
uint256 amount = deposits[from].depositAmount;
require(reward <= rewardBalance, "Not enough rewards");
stakedBalance = stakedBalance.sub(amount);
rewardBalance = rewardBalance.sub(reward);
deposits[from].paid = true;
hasStaked[from] = false; //Check-Effects-Interactions pattern
bool principalPaid = _payDirect(from, amount, tokenAddress);
bool rewardPaid = _payDirect(from, reward, rewardTokenAddress);
require(principalPaid && rewardPaid, "Error paying");
emit PaidOut(tokenAddress, rewardTokenAddress, from, amount, reward);
return true;
}
/**
* @dev to calculate the price of BNF per UNIv2 in the LP
*/
function getPeggedValue() private returns (uint256) {
ERC20Interface = IERC20(tokenAddress);
uint256 getReserves;
if (ERC20Interface.token0() == rewardTokenAddress) {
(getReserves, , ) = ERC20Interface.getReserves();
} else {
(, getReserves, ) = ERC20Interface.getReserves();
}
uint256 totalSupply = ERC20Interface.totalSupply();
return (getReserves.mul(10**18).div(totalSupply));
}
function emergencyWithdraw() external returns (bool) {
address from = msg.sender;
require(hasStaked[from], "No stakes found for user");
require(!deposits[from].paid, "Already paid out");
return (_emergencyWithdraw(from));
}
function _emergencyWithdraw(address from) private returns (bool) {
uint256 amount = deposits[from].depositAmount;
stakedBalance = stakedBalance.sub(amount);
deposits[from].paid = true;
hasStaked[from] = false; //Check-Effects-Interactions pattern
bool principalPaid = _payDirect(from, amount, tokenAddress);
require(principalPaid, "Error paying");
emit PaidOut(tokenAddress, address(0), from, amount, 0);
return true;
}
/**
* @param
* from user wallet address
* @dev to calculate the rewards based on user staked 'amount'
*/
function calculate(address from) external view returns (uint256) {
return _calculate(from);
}
function _calculate(address from) private view returns (uint256) {
if (!hasStaked[from]) return 0;
(uint256 amount, uint256 depositTime, uint64 userIndex) = (
deposits[from].depositAmount,
deposits[from].depositTime,
deposits[from].userIndex
);
uint256 time;
uint256 interest;
uint256 initialAmount = amount;
for (uint64 i = userIndex; i < index; i++) {
time = rates[i + 1].timeStamp.sub(depositTime);
interest = (
amount.mul(rates[i].newInterestRate).mul(time).div(315360000000)
);
amount += interest;
depositTime = rates[i + 1].timeStamp;
}
time = block.timestamp.sub(depositTime);
interest = (amount.mul(rate).mul(time).div(315360000000));
amount += interest;
return (amount.sub(initialAmount));
}
function _payMe(
address payer,
uint256 amount,
address token
) private returns (bool) {
return _payTo(payer, address(this), amount, token);
}
function _payTo(
address allower,
address receiver,
uint256 amount,
address token
) private _hasAllowance(allower, amount, token) returns (bool) {
// Request to transfer amount from the contract to receiver.
// contract does not own the funds, so the allower must have added allowance to the contract
// Allower is the original owner.
ERC20Interface = IERC20(token);
return ERC20Interface.transferFrom(allower, receiver, amount);
}
function _payDirect(
address to,
uint256 amount,
address token
) private returns (bool) {
ERC20Interface = IERC20(token);
return ERC20Interface.transfer(to, amount);
}
modifier _hasAllowance(
address allower,
uint256 amount,
address token
) {
// Make sure the allower has provided the right allowance.
ERC20Interface = IERC20(token);
uint256 ourAllowance = ERC20Interface.allowance(allower, address(this));
require(amount <= ourAllowance, "Make sure to add enough allowance");
_;
}
}
|
returns user staking data/
|
function userDeposits(address user)
external
view
returns (
uint256,
uint256,
uint256,
bool
)
{
if (hasStaked[user]) {
return (
deposits[user].depositAmount,
deposits[user].depositTime,
deposits[user].userIndex,
deposits[user].paid
);
}
}
| 14,735,802 |
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Owned.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
date: 2018-2-26
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
pragma solidity 0.4.24;
/**
* @title A contract with an owner.
* @notice Contract ownership can be transferred by first nominating the new owner,
* who must then accept the ownership, which prevents accidental incorrect ownership transfers.
*/
contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SelfDestructible.sol
version: 1.2
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind. All ether contained in the contract
is forwarded to a nominated beneficiary upon destruction.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be destroyed by its owner after a delay elapses.
*/
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
/**
* @notice Set the beneficiary address of this contract.
* @dev Only the contract owner may call this. The provided beneficiary must be non-null.
* @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
*/
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
/**
* @notice Begin the self-destruction counter of this contract.
* Once the delay has elapsed, the contract may be self-destructed.
* @dev Only the contract owner may call this.
*/
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
/**
* @notice Terminate and reset the self-destruction timer.
* @dev Only the contract owner may call this.
*/
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
/**
* @notice If the self-destruction delay has elapsed, destroy this contract and
* remit any ether it owns to the beneficiary address.
* @dev Only the contract owner may call this.
*/
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Pausable.sol
version: 1.0
author: Kevin Brown
date: 2018-05-22
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be marked as
paused. It also defines a modifier which can be used by the
inheriting contract to prevent actions while paused.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be paused by its owner
*/
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused)
external
onlyOwner
{
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SafeDecimalMath.sol
version: 1.0
author: Anton Jurisevic
date: 2018-2-5
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals (including fiat, ether, and nomin quantities).
*/
contract SafeDecimalMath {
/* Number of decimal places in the representation. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint public constant UNIT = 10 ** uint(decimals);
/**
* @return True iff adding x and y will not overflow.
*/
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/**
* @return The result of adding x and y, throwing an exception in case of overflow.
*/
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y, "Safe add failed");
return x + y;
}
/**
* @return True iff subtracting y from x will not overflow in the negative direction.
*/
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/**
* @return The result of subtracting y from x, throwing an exception in case of overflow.
*/
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x, "Safe sub failed");
return x - y;
}
/**
* @return True iff multiplying x and y would not overflow.
*/
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/**
* @return The result of multiplying x and y, throwing an exception in case of overflow.
*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y, "Safe mul failed");
return p;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals. Throws an exception in case of overflow.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256.
* Incidentally, the internal division always rounds down: one could have rounded to the nearest integer,
* but then one would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return safeMul(x, y) / UNIT;
}
/**
* @return True iff the denominator of x/y is nonzero.
*/
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/**
* @return The result of dividing x by y, throwing an exception if the divisor is zero.
*/
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
/* Although a 0 denominator already throws an exception,
* it is equivalent to a THROW operation, which consumes all gas.
* A require statement emits REVERT instead, which remits remaining gas. */
require(y != 0, "Denominator cannot be zero");
return x / y;
}
/**
* @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().
*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Reintroduce the UNIT factor that will be divided out by y. */
return safeDiv(safeMul(x, UNIT), y);
}
/**
* @dev Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range.
*/
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: State.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: TokenState.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token State
* @notice Stores balance information of an ERC20 token contract.
*/
contract TokenState is State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _associatedContract The ERC20 contract whose state this composes.
*/
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxy.sol
version: 1.3
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
This proxy has the capacity to toggle between DELEGATECALL
and CALL style proxy functionality.
The former executes in the proxy's context, and so will preserve
msg.sender and store data at the proxy address. The latter will not.
Therefore, any contract the proxy wraps in the CALL style must
implement the Proxyable interface, in order that it can pass msg.sender
into the underlying contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
/* Copy call data into free memory region. */
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* Forward all gas and call data to the target contract. */
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
/* Revert if the call failed, otherwise return the result. */
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
/* Here we are as above, but must send the messageSender explicitly
* since we are using CALL rather than DELEGATECALL. */
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxyable.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxyable contract that works hand in hand with the Proxy contract
to allow for anyone to interact with the underlying contract both
directly and through the proxy.
-----------------------------------------------------------------
*/
// This contract should be treated like an abstract contract
contract Proxyable is Owned {
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.0
author: Kevin Brown
date: 2018-08-06
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract offers a modifer that can prevent reentrancy on
particular actions. It will not work if you put it on multiple
functions that can be called from each other. Specifically guard
external entry points to the contract with the modifier only.
-----------------------------------------------------------------
*/
contract ReentrancyPreventer {
/* ========== MODIFIERS ========== */
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A partial ERC20 token contract, designed to operate with a proxy.
To produce a complete ERC20 token, transfer and transferFrom
tokens must be implemented, using the provided _byProxy internal
functions.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
*/
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer {
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields.
* Note that the decimals field is defined in SafeDecimalMath.*/
string public name;
string public symbol;
uint public totalSupply;
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _tokenState The TokenState contract address.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value)
internal
preventReentrancy
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
/*
If we're transferring to a contract and it implements the havvenTokenFallback function, call it.
This isn't ERC223 compliant because:
1. We don't revert if the contract doesn't implement havvenTokenFallback.
This is because many DEXes and other contracts that expect to work with the standard
approve / transferFrom workflow don't implement tokenFallback but can still process our tokens as
usual, so it feels very harsh and likely to cause trouble if we add this restriction after having
previously gone live with a vanilla ERC20.
2. We don't pass the bytes parameter.
This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884
3. We also don't let the user use a custom tokenFallback. We figure as we're already not standards
compliant, there won't be a use case where users can't just implement our specific function.
As such we've called the function havvenTokenFallback to be clear that we are not following the standard.
*/
// Is the to address a contract? We can check the code size on that address and know.
uint length;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Retrieve the size of the code on the recipient address
length := extcodesize(to)
}
// If there's code there, it's a contract
if (length > 0) {
// Now we need to optionally call havvenTokenFallback(address from, uint value).
// We can't call it the normal way because that reverts when the recipient doesn't implement the function.
// We'll use .call(), which means we need the function selector. We've pre-computed
// abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas.
// solium-disable-next-line security/no-low-level-calls
to.call(0xcbff5d96, messageSender, value);
// And yes, we specifically don't care if this call fails, so we're not checking the return value.
}
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
/**
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: FeeToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state.
* Additionally charges fees on each transfer.
*/
contract FeeToken is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* ERC20 members are declared in ExternStateToken. */
/* A percentage fee charged on each transfer. */
uint public transferFeeRate;
/* Fee may not exceed 10%. */
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
/* The address with the authority to distribute fees. */
address public feeAuthority;
/* The address that fees will be pooled in. */
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _transferFeeRate The fee rate to charge on transfers.
* @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
/* Constructed transfer fee rate should respect the maximum fee rate. */
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
transferFeeRate = _transferFeeRate;
}
/* ========== SETTERS ========== */
/**
* @notice Set the transfer fee, anywhere within the range 0-10%.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE");
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
/**
* @notice Set the address of the user/contract responsible for collecting or
* distributing fees.
*/
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
/* ========== VIEWS ========== */
/**
* @notice Calculate the Fee charged on top of a value being sent
* @return Return the fee charged
*/
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
/* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
* This is on the basis that transfers less than this value will result in a nil fee.
* Probably too insignificant to worry about, but the following code will achieve it.
* if (fee == 0 && transferFeeRate != 0) {
* return _value;
* }
* return fee;
*/
}
/**
* @notice The value that you would need to send so that the recipient receives
* a specified value.
*/
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
/**
* @notice The amount the recipient will receive if you send a certain number of tokens.
*/
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
/**
* @notice Collected fees sit here until they are distributed.
* @dev The balance of the nomin contract itself is the fee pool.
*/
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Base of transfer functions
*/
function _internalTransfer(address from, address to, uint amount, uint fee)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
/* Emit events for both the transfer itself and the fee. */
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
/**
* @notice ERC20 friendly transfer function.
*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
/**
* @notice ERC20 friendly transferFrom function.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is deducted from the amount sent. */
uint received = amountReceived(value);
uint fee = safeSub(value, received);
/* Reduce the allowance by the amount we're transferring.
* The safeSub call will handle an insufficient allowance. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
/**
* @notice Ability to transfer where the sender pays the fees (not ERC20)
*/
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
/**
* @notice Ability to transferFrom where they sender pays the fees (not ERC20).
*/
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
/* Reduce the allowance by the amount we're transferring. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
/**
* @notice Withdraw tokens from the fee pool into a given account.
* @dev Only the fee authority may call this.
*/
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0), "Must supply an account address to withdraw fees");
/* 0-value withdrawals do nothing. */
if (value == 0) {
return false;
}
/* Safe subtraction ensures an exception is thrown if the balance is insufficient. */
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
/**
* @notice Donate tokens from the sender's balance into the fee pool.
*/
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
/* Empty donations are disallowed. */
uint balance = tokenState.balanceOf(sender);
require(balance != 0, "Must have a balance in order to donate to the fee pool");
/* safeSub ensures the donor has sufficient balance. */
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority, "Only the fee authority can do this action");
_;
}
/* ========== EVENTS ========== */
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Nomin.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each.
Nomins are issuable by Havven holders who have to lock up some
value of their havvens to issue H * Cmax nomins. Where Cmax is
some value less than 1.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once
per fee period.
-----------------------------------------------------------------
*/
contract Nomin is FeeToken {
/* ========== STATE VARIABLES ========== */
Havven public havven;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
// Nomin transfers incur a 15 bp fee by default.
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
/* ========== CONSTRUCTOR ========== */
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven, // The havven contract is the fee authority.
_owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_havven) != 0, "_havven cannot be 0");
require(_owner != 0, "_owner cannot be 0");
// It should not be possible to transfer to the fee pool directly (or confiscate its balance).
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
// havven should be set as the feeAuthority after calling this depending on
// havven's internal logic
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address");
frozen[target] = false;
emitAccountUnfrozen(target);
}
/* Allow havven to issue a certain number of
* nomins from an account. */
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
/* Allow havven to burn a certain number of
* nomins from an account. */
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
/* ========== MODIFIERS ========== */
modifier onlyHavven() {
require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: LimitedSetup.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
/**
* @title Any function decorated with the modifier this contract provides
* deactivates after a specified setup period.
*/
contract LimitedSetup {
uint setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: HavvenEscrow.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed havvens and free them at given schedules.
*/
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
/* The corresponding Havven contract. */
Havven public havven;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of havvens vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total vested havven balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining vested balance, for verifying the actual havven balance of this contract against. */
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
uint constant MAX_VESTING_ENTRIES = 20;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, havven quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of havvens associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, havven quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Withdraws a quantity of havvens back to the havven contract.
* @dev This may only be called by the owner during the contract's setup period.
*/
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
/**
* @notice Destroy the vesting information associated with an account.
*/
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* This may only be called by the owner during the contract's setup period.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists.
* @param account The account to append a new vesting entry to.
* @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
* @param quantity The quantity of havvens that will vest.
*/
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
/* No empty or already-passed vesting entries allowed. */
require(now < time, "Time must be in the future");
require(quantity != 0, "Quantity cannot be zero");
/* There must be enough balance in the contract to provide for the vesting entry. */
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry");
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested havvens earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/**
* @notice Construct a vesting schedule to release a quantities of havvens
* over a series of intervals.
* @dev Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing.
* This may only be called by the owner during the contract's setup period.
*/
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/**
* @notice Allow a user to withdraw any havvens in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Havven.sol
version: 1.2
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens may participate in nomin confiscation votes, they
may also have the right to issue nomins at the discretion of the
foundation for this version of the contract.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins. Thus an account may only
withdraw the fees owed to them for the previous period, and may only do
so once per period. Any unclaimed fees roll over into the common pot for
the next period.
== Average Balance Calculations ==
The fee entitlement of a havven holder is proportional to their average
issued nomin balance over the last fee period. This is computed by
measuring the area under the graph of a user's issued nomin balance over
time, and then when a new fee period begins, dividing through by the
duration of the fee period.
We need only update values when the balances of an account is modified.
This occurs when issuing or burning for issued nomin balances,
and when transferring for havven balances. This is for efficiency,
and adds an implicit friction to interacting with havvens.
A havven holder pays for his own recomputation whenever he wants to change
his position, which saves the foundation having to maintain a pot dedicated
to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to n
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
== Issuance and Burning ==
In this version of the havven contract, nomins can only be issued by
those that have been nominated by the havven foundation. Nomins are assumed
to be valued at $1, as they are a stable unit of account.
All nomins issued require a proportional value of havvens to be locked,
where the proportion is governed by the current issuance ratio. This
means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued.
i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up.
To determine the value of some amount of havvens(H), an oracle is used to push
the price of havvens (P_H) in dollars to the contract. The value of H
would then be: H * P_H.
Any havvens that are locked up by this issuance process cannot be transferred.
The amount that is locked floats based on the price of havvens. If the price
of havvens moves up, less havvens are locked, so they can be issued against,
or transferred freely. If the price of havvens moves down, more havvens are locked,
even going above the initial wallet balance.
-----------------------------------------------------------------
*/
/**
* @title Havven ERC20 contract.
* @notice The Havven contracts does not only facilitate transfers and track balances,
* but it also computes the quantity of fees each havven holder is entitled to.
*/
contract Havven is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* A struct for handing values associated with average balance calculations */
struct IssuanceData {
/* Sums of balances*duration in the current fee period.
/* range: decimals; units: havven-seconds */
uint currentBalanceSum;
/* The last period's average balance */
uint lastAverageBalance;
/* The last time the data was calculated */
uint lastModified;
}
/* Issued nomin balances for individual fee entitlements */
mapping(address => IssuanceData) public issuanceData;
/* The total number of issued nomins for determining fee entitlements */
IssuanceData public totalIssuanceData;
/* The time the current fee period began */
uint public feePeriodStartTime;
/* The time the last fee period began */
uint public lastFeePeriodStartTime;
/* Fee periods will roll over in no shorter a time than this.
* The fee period cannot actually roll over until a fee-relevant
* operation such as withdrawal or a fee period duration update occurs,
* so this is just a target, and the actual duration may be slightly longer. */
uint public feePeriodDuration = 4 weeks;
/* ...and must target between 1 day and six months. */
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
/* The quantity of nomins that were in the fee pot at the time */
/* of the last fee rollover, at feePeriodStartTime. */
uint public lastFeesCollected;
/* Whether a user has withdrawn their last fees */
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
/* The address of the oracle which pushes the havven price to this contract */
address public oracle;
/* The price of havvens written in UNIT */
uint public price;
/* The time the havven price was last updated */
uint public lastPriceUpdateTime;
/* How long will the contract assume the price of havvens is correct */
uint public priceStalePeriod = 3 hours;
/* A quantity of nomins greater than this ratio
* may not be issued against a given value of havvens. */
uint public issuanceRatio = UNIT / 5;
/* No more nomins may be issued than the value of havvens backing them. */
uint constant MAX_ISSUANCE_RATIO = UNIT;
/* Whether the address can issue nomins or not. */
mapping(address => bool) public isIssuer;
/* The number of currently-outstanding nomins the user has issued. */
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _tokenState A pre-populated contract containing token balances.
* If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
// It is not valid in general to skip those with no currently-issued nomins.
// But for this release, issuers with nonzero issuanceData have current issuance.
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
/* ========== SETTERS ========== */
/**
* @notice Set the associated Nomin contract to collect fees from.
* @dev Only the contract owner may call this.
*/
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
/**
* @notice Set the associated havven escrow contract.
* @dev Only the contract owner may call this.
*/
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
/**
* @notice Set the targeted fee period duration.
* @dev Only callable by the contract owner. The duration must fall within
* acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period
* may roll over if the target duration was shortened sufficiently.
*/
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION,
"Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION");
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
*/
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
/**
* @notice Set the stale period on the updated havven price
* @dev No max/minimum, as changing it wont influence anything but issuance by the foundation
*/
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
/**
* @notice Set the issuanceRatio for issuance calculations.
* @dev Only callable by the contract owner.
*/
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
/**
* @notice Set whether the specified can issue nomins or not.
*/
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
/* ========== VIEWS ========== */
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transfer_byProxy(sender, to, value);
return true;
}
/**
* @notice ERC20 transferFrom function.
*/
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transferFrom_byProxy(sender, from, to, value);
return true;
}
/**
* @notice Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account.
*/
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
/* Do not deposit fees into frozen accounts. */
require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts");
/* Check the period has rolled over first. */
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
/* Only allow accounts to withdraw fees once per period. */
require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period");
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
/* Sender receives a share of last period's collected fees proportional
* with their average fraction of the last period's issued nomins. */
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
/**
* @notice Update the havven balance averages since the last transfer
* or entitlement adjustment.
* @dev Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call.
* Also, this will adjust the total issuance at the same time.
*/
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
/* update the total balances first */
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
/**
* @notice Compute the new IssuanceData on the old balance
*/
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
/* The balance was last updated before the previous fee period, so the average
* balance in this period is their pre-transfer balance. */
lastAverageBalance = preBalance;
} else {
/* The balance was last updated during the previous fee period. */
/* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified.
* implies these quantities are strictly positive. */
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
/* Roll over to the next fee period. */
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
/* The balance was last updated during the current fee period. */
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
/**
* @notice Recompute and return the given account's last average balance.
*/
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
/**
* @notice Issue nomins against the sender's havvens.
* @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer.
*/
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
/* No need to check if price is stale, as it is checked in issuableNomins. */
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins");
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
/**
* @notice Burn nomins to clear issued nomins/free havvens.
*/
function burnNomins(uint amount)
/* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
/* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */
nomin.burn(sender, amount);
/* This safe sub ensures amount <= number issued */
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
/**
* @notice Check if the fee period has rolled over. If it has, set the new fee period start
* time, and record the fees collected in the nomin contract.
*/
function rolloverFeePeriodIfElapsed()
public
{
/* If the fee period has rolled over... */
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
/* ========== Issuance/Burning ========== */
/**
* @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any
* already issued nomins.
*/
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
/**
* @notice The remaining nomins an issuer can issue against their total havven quantity.
*/
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
/**
* @notice The total havvens owned by this account, both escrowed and unescrowed,
* against which nomins 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 bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
/**
* @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral.
*/
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
/**
* @notice Collateral that has been locked due to issuance, and cannot be
* transferred to other addresses. This is capped at the account's total collateral.
*/
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
/**
* @notice Collateral that is not locked and available for issuance.
*/
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
/**
* @notice The number of havvens that are free to be transferred by an account.
* @dev If they have enough available Havvens, it could be that
* their havvens are escrowed, however the transfer would then
* fail. This means that escrowed havvens are locked first,
* and then the actual transferable ones.
*/
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
// In the case where the issuanceDraft exceeds the collateral, nothing is free
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
// In the case where the draft exceeds the escrow, but not the whole collateral
// return the fraction of the balance that remains free
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
// In the case where the draft doesn't exceed the escrow, return the entire balance
return bal;
}
/**
* @notice The value in USD for a given amount of HAV
*/
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
/**
* @notice The value in HAV for a given amount of USD
*/
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
/**
* @notice Access point for the oracle to update the price of havvens.
*/
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle /* Should be callable only by the oracle. */
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
/* Check the fee period rollover within this as the price should be pushed every 15min. */
rolloverFeePeriodIfElapsed();
}
/**
* @notice Check if the price of havvens hasn't been updated for longer than the stale period.
*/
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/* ========== MODIFIERS ========== */
modifier requireIssuer(address account)
{
require(isIssuer[account], "Must be issuer to perform this action");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier priceNotStale
{
require(!priceIsStale(), "Price must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION -----------------------------------------------------------------
file: IssuanceController.sol
version: 2.0
author: Kevin Brown
date: 2018-07-18
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Issuance controller contract. The issuance controller provides
a way for users to acquire nomins (Nomin.sol) and havvens
(Havven.sol) by paying ETH and a way for users to acquire havvens
(Havven.sol) by paying nomins. Users can also deposit their nomins
and allow other users to purchase them with ETH. The ETH is sent
to the user who offered their nomins for sale.
This smart contract contains a balance of each currency, and
allows the owner of the contract (the Havven Foundation) to
manage the available balance of havven at their discretion, while
users are allowed to deposit and withdraw their own nomin deposits
if they have not yet been taken up by another user.
-----------------------------------------------------------------
*/
/**
* @title Issuance Controller Contract.
*/
contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable {
/* ========== STATE VARIABLES ========== */
Havven public havven;
Nomin public nomin;
// Address where the ether raised is transfered to
address public fundsWallet;
/* The address of the oracle which pushes the USD price havvens and ether to this contract */
address public oracle;
/* Do not allow the oracle to submit times any further forward into the future than
this constant. */
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
/* How long will the contract assume the price of any asset is correct */
uint public priceStalePeriod = 3 hours;
/* The time the prices were last updated */
uint public lastPriceUpdateTime;
/* The USD price of havvens denominated in UNIT */
uint public usdToHavPrice;
/* The USD price of ETH denominated in UNIT */
uint public usdToEthPrice;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _owner The owner of this contract.
* @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging.
* @param _havven The Havven contract we'll interact with for balances and sending.
* @param _nomin The Nomin contract we'll interact with for balances and sending.
* @param _oracle The address which is able to update price information.
* @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT.
* @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT.
*/
constructor(
// Ownable
address _owner,
// Funds Wallet
address _fundsWallet,
// Other contracts needed
Havven _havven,
Nomin _nomin,
// Oracle values - Allows for price updates
address _oracle,
uint _usdToEthPrice,
uint _usdToHavPrice
)
/* Owned is initialised in SelfDestructible */
SelfDestructible(_owner)
Pausable(_owner)
public
{
fundsWallet = _fundsWallet;
havven = _havven;
nomin = _nomin;
oracle = _oracle;
usdToEthPrice = _usdToEthPrice;
usdToHavPrice = _usdToHavPrice;
lastPriceUpdateTime = now;
}
/* ========== SETTERS ========== */
/**
* @notice Set the funds wallet where ETH raised is held
* @param _fundsWallet The new address to forward ETH and Nomins to
*/
function setFundsWallet(address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
emit FundsWalletUpdated(fundsWallet);
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
* @param _oracle The new oracle address
*/
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
/**
* @notice Set the Nomin contract that the issuance controller uses to issue Nomins.
* @param _nomin The new nomin contract target
*/
function setNomin(Nomin _nomin)
external
onlyOwner
{
nomin = _nomin;
emit NominUpdated(_nomin);
}
/**
* @notice Set the Havven contract that the issuance controller uses to issue Havvens.
* @param _havven The new havven contract target
*/
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/**
* @notice Set the stale period on the updated price variables
* @param _time The new priceStalePeriod
*/
function setPriceStalePeriod(uint _time)
external
onlyOwner
{
priceStalePeriod = _time;
emit PriceStalePeriodUpdated(priceStalePeriod);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Access point for the oracle to update the prices of havvens / eth.
* @param newEthPrice The current price of ether in USD, specified to 18 decimal places.
* @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places.
* @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don't consider stale prices as current in times of heavy network congestion.
*/
function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent)
external
onlyOracle
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
usdToEthPrice = newEthPrice;
usdToHavPrice = newHavvenPrice;
lastPriceUpdateTime = timeSent;
emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime);
}
/**
* @notice Fallback function (exchanges ETH to nUSD)
*/
function ()
external
payable
{
exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to nUSD.
*/
function exchangeEtherForNomins()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
// The multiplication works here because usdToEthPrice is specified in
// 18 decimal places, just like our currency base.
uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// Send the nomins.
// Note: Fees are calculated by the Nomin contract, so when
// we request a specific transfer here, the fee is
// automatically deducted and sent to the fee pool.
nomin.transfer(msg.sender, requestedToPurchase);
emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase);
return requestedToPurchase;
}
/**
* @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert.
*/
function exchangeEtherForNominsAtRate(uint guaranteedRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
require(guaranteedRate == usdToEthPrice);
return exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to HAV.
*/
function exchangeEtherForHavvens()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForEther(msg.value);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("ETH", msg.value, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rates.
* @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert.
* @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert.
*/
function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedEtherRate == usdToEthPrice);
require(guaranteedHavvenRate == usdToHavPrice);
return exchangeEtherForHavvens();
}
/**
* @notice Exchange nUSD for Havvens
* @param nominAmount The amount of nomins the user wishes to exchange.
*/
function exchangeNominsForHavvens(uint nominAmount)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForNomins(nominAmount);
// Ok, transfer the Nomins to our address.
nomin.transferFrom(msg.sender, this, nominAmount);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("nUSD", nominAmount, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param nominAmount The amount of nomins the user wishes to exchange.
* @param guaranteedRate A rate (havven price) the caller wishes to insist upon.
*/
function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedRate == usdToHavPrice);
return exchangeNominsForHavvens(nominAmount);
}
/**
* @notice Allows the owner to withdraw havvens from this contract if needed.
* @param amount The amount of havvens to attempt to withdraw (in 18 decimal places).
*/
function withdrawHavvens(uint amount)
external
onlyOwner
{
havven.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/**
* @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed.
* @param amount The amount of nomins to attempt to withdraw (in 18 decimal places).
*/
function withdrawNomins(uint amount)
external
onlyOwner
{
nomin.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/* ========== VIEWS ========== */
/**
* @notice Check if the prices haven't been updated for longer than the stale period.
*/
function pricesAreStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of nomins.
* @param amount The amount of nomins (in 18 decimal places) you want to ask about
*/
function havvensReceivedForNomins(uint amount)
public
view
returns (uint)
{
// How many nomins would we receive after the transfer fee?
uint nominsReceived = nomin.amountReceived(amount);
// And what would that be worth in havvens based on the current price?
return safeDiv_dec(nominsReceived, usdToHavPrice);
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function havvensReceivedForEther(uint amount)
public
view
returns (uint)
{
// How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)?
uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice);
// Now, how many HAV will that USD amount buy?
return havvensReceivedForNomins(valueSentInNomins);
}
/**
* @notice Calculate how many nomins you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function nominsReceivedForEther(uint amount)
public
view
returns (uint)
{
// How many nomins would that amount of ether be worth?
uint nominsTransferred = safeMul_dec(amount, usdToEthPrice);
// And how many of those would you receive after a transfer (deducting the transfer fee)
return nomin.amountReceived(nominsTransferred);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier pricesNotStale
{
require(!pricesAreStale(), "Prices must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event FundsWalletUpdated(address newFundsWallet);
event OracleUpdated(address newOracle);
event NominUpdated(Nomin newNominContract);
event HavvenUpdated(Havven newHavvenContract);
event PriceStalePeriodUpdated(uint priceStalePeriod);
event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent);
event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount);
}
|
Collateral that has been locked due to issuance, and cannot be transferred to other addresses. This is capped at the account&39;s total collateral./
|
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
| 2,140,208 |
./full_match/1/0x5349E94435Cc9Cab9FfB40A492DA46935052733A/sources/cache/solpp-generated-contracts/zksync/libraries/TransactionValidator.sol
|
Based on the full L2 gas limit (that includes the block overhead) and other properties of the transaction, returns the l2GasLimit for the body of the transaction (the actual execution). _totalGasLimit The L2 gas limit that includes both the overhead for processing the block and the L2 gas needed to process the transaction itself (i.e. the actual l2GasLimit that will be used for the transaction). _gasPricePerPubdata The L2 gas price for each byte of pubdata. _encodingLength The length of the ABI-encoding of the transaction. We enforce the fact that `_totalGasLimit >= overhead` explicitly above.
|
function getTransactionBodyGasLimit(
uint256 _totalGasLimit,
uint256 _gasPricePerPubdata,
uint256 _encodingLength
) internal pure returns (uint256 txBodyGasLimit) {
uint256 overhead = getOverheadForTransaction(_totalGasLimit, _gasPricePerPubdata, _encodingLength);
unchecked {
txBodyGasLimit = _totalGasLimit - overhead;
}
}
| 3,023,175 |
./full_match/1/0xEeb717450af1C9E3b8493C0B62855dDCB28c3489/sources/contracts/CryptoFBoys.sol
|
Increment operation cannot overflow.
|
function mintBatch(uint256 count) public onlyOwner {
uint256 startAt = currentTokenId;
while (currentTokenId < startAt + count) {
_mint(msg.sender, currentTokenId);
unchecked {
currentTokenId++;
}
}
}
| 9,746,098 |
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title 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 Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
/**
* @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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) public 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 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 KryptoroToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `StandardToken` functions.
*/
contract KryptoroToken is StandardToken, Destructible {
string public constant name = "KRYPTORO Coin";
string public constant symbol = "KTO";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 100 * 1000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function KryptoroToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
/**
* @title KTOCrowdsale
* @dev KTOCrowdsale is a completed contract for managing a token crowdsale.
* KTOCrowdsale have a start and end timestamps, where investors can make
* token purchases and the KTOCrowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract KTOCrowdsale is Ownable{
using SafeMath for uint256;
// The token being sold
KryptoroToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event TokenContractUpdated(bool state);
event WalletAddressUpdated(bool state);
function KTOCrowdsale() public {
token = createTokenContract();
startTime = 1532332800;
endTime = 1539590400;
rate = 612;
wallet = 0x34367d515ff223a27985518f2780cccc4a7e0fc9;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (KryptoroToken) {
return new KryptoroToken();
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
token.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool nonZeroPurchase = msg.value != 0;
bool withinPeriod = now >= startTime && now <= endTime;
return nonZeroPurchase && withinPeriod;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool timeEnded = now > endTime;
return timeEnded;
}
// update token contract
function updateKryptoroToken(address _tokenAddress) onlyOwner{
require(_tokenAddress != address(0));
token.transferOwnership(_tokenAddress);
TokenContractUpdated(true);
}
// update wallet address
function updateWalletAddress(address _newWallet) onlyOwner {
require(_newWallet != address(0));
wallet = _newWallet;
WalletAddressUpdated(true);
}
// transfer tokens
function transferTokens(address _to, uint256 _amount) onlyOwner {
require(_to != address(0));
token.transfer(_to, _amount);
}
}
|
Constructor that gives msg.sender all of existing tokens./
|
function KryptoroToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
| 10,417,377 |
./partial_match/1/0xAe46E888aF6318aED82FE715b1b98b78F74e7b65/sources/LiquidityPoolV1Converter.sol
|
removes liquidity (reserve) from the pool _reserveTokens address of each reserve token _reserveMinReturnAmounts minimum return-amount of each reserve token _totalSupply token total supply _amount token amount return the amount of each reserve token granted for the given amount of pool tokens/ transfer each one of the reserve amounts from the pool to the user dispatch the `TokenRateUpdate` event for the pool token
|
function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount)
private
returns (uint256[] memory)
{
syncReserveBalances();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 newPoolTokenSupply = _totalSupply.sub(_amount);
uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, _reserveTokens, _totalSupply, formula);
for (uint256 i = 0; i < _reserveTokens.length; i++) {
IERC20Token reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
uint256 newReserveBalance = reserves[reserveToken].balance.sub(reserveAmount);
reserves[reserveToken].balance = newReserveBalance;
if (reserveToken == ETH_RESERVE_ADDRESS)
msg.sender.transfer(reserveAmount);
else
safeTransfer(reserveToken, msg.sender, reserveAmount);
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);
dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight);
}
}
| 9,362,120 |
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// 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;
}
}
// File @openzeppelin/contracts/access/[email protected]
// MIT
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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/MVM/iMVM_DiscountOracle.sol
// MIT
pragma solidity ^0.8.9;
interface iMVM_DiscountOracle{
function setDiscount(
uint256 _discount
) external;
function setMinL2Gas(
uint256 _minL2Gas
) external;
function setWhitelistedXDomainSender(
address _sender,
bool _isWhitelisted
) external;
function isXDomainSenderAllowed(
address _sender
) view external returns(bool);
function setAllowAllXDomainSenders(
bool _allowAllXDomainSenders
) external;
function getMinL2Gas() view external returns(uint256);
function getDiscount() view external returns(uint256);
function processL2SeqGas(address sender, uint256 _chainId) external payable;
}
// File contracts/libraries/resolver/Lib_AddressManager.sol
// MIT
pragma solidity ^0.8.9;
/* External Imports */
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(string indexed _name, address _newAddress, address _oldAddress);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address) external onlyOwner {
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// File contracts/libraries/resolver/Lib_AddressResolver.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// File contracts/libraries/rlp/Lib_RLPReader.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({ length: _in.length, ptr: ptr });
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value.");
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length.");
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })
);
out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset });
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value.");
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in) internal pure returns (string memory) {
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, "Invalid RLP bytes32 value.");
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, "Invalid RLP boolean value.");
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1");
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, "RLP item cannot be null.");
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, "Invalid RLP long string length.");
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string.");
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, "Invalid RLP short list.");
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, "Invalid RLP long list length.");
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, "Invalid RLP long list.");
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// File contracts/libraries/rlp/Lib_RLPWriter.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// File contracts/libraries/utils/Lib_BytesUtils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
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)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
// File contracts/libraries/utils/Lib_Bytes32Utils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// File contracts/libraries/codec/Lib_OVMCodec.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) {
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) {
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// File contracts/libraries/utils/Lib_MerkleTree.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) {
require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash.");
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i)];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
) internal pure returns (bool) {
require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero.");
require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds.");
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot));
} else {
computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i]));
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(uint256 _in) private pure returns (uint256) {
require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0.");
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (((uint256(1) << i) - 1) << i) != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint256(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// File contracts/L1/rollup/IChainStorageContainer.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Set an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _index position.
* @param _object A 32 byte value to insert into the container.
*/
function setByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external;
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _chainId identity for the l2 chain.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @param _chainId identity for the l2 chain.
* @return Container global metadata field.
*/
function getGlobalMetadataByChainId(
uint256 _chainId
)
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @param _chainId identity for the l2 chain.
* @return Number of objects in the container.
*/
function lengthByChainId(
uint256 _chainId
)
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _chainId identity for the l2 chain.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function getByChainId(
uint256 _chainId,
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// File contracts/L1/rollup/IStateCommitmentChain.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
/**
* @title IStateCommitmentChain
*/
interface IStateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
function batches() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
) external view returns (bool _verified);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
external
view
returns (
bool _inside
);
/********************
* chain id added func *
********************/
/**
* Retrieves the total number of elements submitted.
* @param _chainId identity for the l2 chain.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @param _chainId identity for the l2 chain.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @param _chainId identity for the l2 chain.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestampByChainId(uint256 _chainId)
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _chainId identity for the l2 chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatchByChainId(
uint256 _chainId,
bytes32[] calldata _batch,
uint256 _shouldStartAtElement,
string calldata proposer
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatchByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _chainId identity for the l2 chain.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitmentByChainId(
uint256 _chainId,
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindowByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// File contracts/MVM/MVM_Verifier.sol
// MIT
pragma solidity ^0.8.9;
/* Contract Imports */
/* External Imports */
contract MVM_Verifier is Lib_AddressResolver{
// second slot
address public metis;
enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS}
event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp);
event Verify1(uint256 cIndex, address verifier);
event Verify2(uint256 cIndex, address verifier);
event Finalize(uint256 cIndex, address sender, SETTLEMENT result);
event Penalize(address sender, uint256 stakeLost);
event Reward(address target, uint256 amount);
event Claim(address sender, uint256 amount);
event Withdraw(address sender, uint256 amount);
event Stake(address verifier, uint256 amount);
event SlashSequencer(uint256 chainID, address seq);
/*************
* Constants *
*************/
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
//challenge info
struct Challenge {
address challenger;
uint256 chainID;
uint256 index;
Lib_OVMCodec.ChainBatchHeader header;
uint256 timestamp;
uint256 numQualifiedVerifiers;
uint256 numVerifiers;
address[] verifiers;
bool done;
}
mapping (address => uint256) public verifier_stakes;
mapping (uint256 => mapping (address=>bytes)) private challenge_keys;
mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes;
mapping (uint256 => mapping (address=>bytes)) private challenge_hashes;
mapping (address => uint256) public rewards;
mapping (address => uint8) public absence_strikes;
mapping (address => uint8) public consensus_strikes;
// only one active challenge for each chain chainid=>cIndex
mapping (uint256 => uint256) public chain_under_challenge;
// white list
mapping (address => bool) public whitelist;
bool useWhiteList;
address[] public verifiers;
Challenge[] public challenges;
uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase
uint public activeChallenges;
uint256 public minStake;
uint256 public seqStake;
uint256 public numQualifiedVerifiers;
uint FAIL_THRESHOLD = 2; // 1 time grace
uint ABSENCE_THRESHOLD = 4; // 2 times grace
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_Verifier: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
modifier onlyStaked {
require(isSufficientlyStaked(msg.sender), "insufficient stake");
_;
}
constructor(
)
Lib_AddressResolver(address(0))
{
}
// add stake as a verifier
function verifierStake(uint256 stake) public onlyWhitelisted{
require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
// start a new challenge
// @param chainID chainid
// @param header chainbatch header
// @param proposedHash encrypted hash of the correct state
// @param keyhash hash of the decryption key
//
// @dev why do we ask for key and keyhash? because we want verifiers compute the state instead
// of just copying from other verifiers.
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
// while the root is encrypted, the timestamp is available in the extradata field of the header
require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window");
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
// house keeping
challenge_hashes[cIndex][msg.sender] = proposedHash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++; // the challenger
// this will prevent stake change
activeChallenges++;
chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
// phase 1 of the verify, provide an encrypted hash and the hash of the decryption key
// @param cIndex index of the challenge
// @param hash encrypted hash of the correct state (for the index referred in the challenge)
// @param keyhash hash of the decryption key
function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{
require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender");
challenge_hashes[cIndex][msg.sender] = hash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++;
emit Verify1(cIndex, msg.sender);
}
// phase 2 of the verify, provide the actual key to decrypt the hash
// @param cIndex index of the challenge
// @param key the decryption key
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
//verify whether the key matches the keyhash initially provided.
require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match");
if (msg.sender == challenges[cIndex].challenger) {
//decode the root in the header too
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
// not ready to finalize. do nothing
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
// not qualified as a verifier
continue;
}
//record the agreement
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
//agree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
} else if (challenge_keys[cIndex][verifiers[i]].length == 0) {
//absent
absence_strikes[verifiers[i]] += 2;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
} else {
//disagree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
// wrong header, penalize the challenger
reward += penalize(challenge.challenger);
// reward the disagrees. but no penalty on agrees because the input
// is garbage.
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) {
// the absent verifiers get a absense strike. no other penalties. already done
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
// no consensus, challenge failed.
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else {
// reached agreement. delete the batch root and slash the sequencer if the header is still valid
if(stateChain.insideFraudProofWindow(challenge.header)) {
// this header needs to be within the window
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
// temporary for the p1 of the decentralization roadmap
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
} else {
//not in the window anymore. let it pass... no penalty
emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS);
}
}
} else {
//wasteful challenge, add consensus_strikes to the challenger
consensus_strikes[challenge.challenger] += 2;
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function depositSeqStake(uint256 amount) public onlyManager {
require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed");
seqStake += amount;
emit Stake(msg.sender, amount);
}
function withdrawSeqStake(address to) public onlyManager {
require(seqStake > 0, "no stake");
emit Withdraw(msg.sender, seqStake);
uint256 amount = seqStake;
seqStake = 0;
require(IERC20(metis).transfer(to, amount), "transfer metis failed");
}
function claim() public {
require(rewards[msg.sender] > 0, "no reward to claim");
uint256 amount = rewards[msg.sender];
rewards[msg.sender] = 0;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
emit Claim(msg.sender, amount);
}
function withdraw(uint256 amount) public {
require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
// helper
function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
function isSufficientlyStaked (address target) view public returns(bool) {
return (verifier_stakes[target] >= minStake);
}
// set the length of the time windows for each verification phase
function setVerifyWindow (uint256 window) onlyManager public {
verifyWindow = window;
}
// add the verifier to the whitelist
function setWhiteList(address verifier, bool allowed) public onlyManager {
whitelist[verifier] = allowed;
useWhiteList = true;
}
// allow everyone to be the verifier
function disableWhiteList() public onlyManager {
useWhiteList = false;
}
function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager {
ABSENCE_THRESHOLD = absence_threshold;
FAIL_THRESHOLD = fail_threshold;
}
function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) {
return Lib_MerkleTree.getMerkleRoot(elements);
}
//helper fucntion to encrypt data
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
// helper fucntion to decrypt the data
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
} else {
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
// calculate the rewards
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
} else {
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
// slash the verifier stake
function penalize(address target) internal returns(uint256) {
uint256 stake = verifier_stakes[target];
verifier_stakes[target] = 0;
numQualifiedVerifiers--;
deleteVerifier(target);
emit Penalize(target, stake);
return stake;
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
}
|
Encode integer in big endian binary form with no leading zeroes. TODO: This should be optimized with assembly to save gas costs. _x The integer to encode. return RLP encoded bytes./
|
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
| 366,125 |
./full_match/1/0x25A103A1D6AeC5967c1A4fe2039cdc514886b97e/sources/contracts/RWAHub.sol
|
Admin function to set the minimum amount to redeem _minimumRedemptionAmount The minimum amount required to submit a redemption request/
|
function setMinimumRedemptionAmount(
uint256 _minimumRedemptionAmount
) external onlyRole(MANAGER_ADMIN) {
if (_minimumRedemptionAmount < BPS_DENOMINATOR) {
revert AmountTooSmall();
}
uint256 oldRedeemMinimum = minimumRedemptionAmount;
minimumRedemptionAmount = _minimumRedemptionAmount;
emit MinimumRedemptionAmountSet(oldRedeemMinimum, _minimumRedemptionAmount);
}
| 3,021,974 |
pragma solidity 0.4.23;
/**
* Overflow aware uint math functions.
*
* Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol
*/
contract SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function safeMul(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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
// mitigate short address attack
// thanks to https://github.com/numerai/contract/blob/c182465f82e50ced8dacb3977ec374a892f5fa8c/contracts/Safe.sol#L30-L34.
// TODO: doublecheck implication of >= compared to ==
modifier onlyPayloadSize(uint numWords) {
assert(msg.data.length >= numWords * 32 + 4);
_;
}
}
contract Token { // ERC20 standard
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public 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 StandardToken is Token, SafeMath {
uint256 public totalSupply;
mapping (address => uint256) public index;
mapping (uint256 => Info) public infos;
mapping (address => mapping (address => uint256)) allowed;
struct Info {
uint256 tokenBalances;
address holderAddress;
}
// TODO: update tests to expect throw
function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool success) {
require(_to != address(0));
require(infos[index[msg.sender]].tokenBalances >= _value && _value > 0);
infos[index[msg.sender]].tokenBalances = safeSub(infos[index[msg.sender]].tokenBalances, _value);
infos[index[_to]].tokenBalances = safeAdd(infos[index[_to]].tokenBalances, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// TODO: update tests to expect throw
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool success) {
require(_to != address(0));
require(infos[index[_from]].tokenBalances >= _value && allowed[_from][msg.sender] >= _value && _value > 0);
infos[index[_from]].tokenBalances = safeSub(infos[index[_from]].tokenBalances, _value);
infos[index[_to]].tokenBalances = safeAdd(infos[index[_to]].tokenBalances, _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return infos[index[_owner]].tokenBalances;
}
// 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
function approve(address _spender, uint256 _value) public onlyPayloadSize(2) returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function changeApproval(address _spender, uint256 _oldValue, uint256 _newValue) public onlyPayloadSize(3) returns (bool success) {
require(allowed[msg.sender][_spender] == _oldValue);
allowed[msg.sender][_spender] = _newValue;
emit Approval(msg.sender, _spender, _newValue);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract JCFv2 is StandardToken {
// FIELDS
string public name = "JCFv2";
string public symbol = "JCFv2";
uint256 public decimals = 18;
string public version = "2.0";
uint256 public tokenCap = 1048576000000 * 10**18;
// root control
address public fundWallet;
// control of liquidity and limited control of updatePrice
address public controlWallet;
// fundWallet controlled state variables
// halted: halt buying due to emergency, tradeable: signal that assets have been acquired
bool public halted = false;
bool public tradeable = false;
// -- totalSupply defined in StandardToken
// -- mapping to token balances done in StandardToken
uint256 public minAmount = 0.04 ether;
uint256 public totalHolder;
// map participant address to a withdrawal request
mapping (address => Withdrawal) public withdrawals;
// maps addresses
mapping (address => bool) public whitelist;
// TYPES
struct Withdrawal {
uint256 tokens;
uint256 time; // time for each withdrawal is set to the previousUpdateTime
// uint256 totalAmount;
}
// EVENTS
event Whitelist(address indexed participant);
event AddLiquidity(uint256 ethAmount);
event RemoveLiquidity(uint256 ethAmount);
event WithdrawRequest(address indexed participant, uint256 amountTokens, uint256 requestTime);
event Withdraw(address indexed participant, uint256 amountTokens, uint256 etherAmount);
event Burn(address indexed burner, uint256 value);
// MODIFIERS
modifier isTradeable {
require(tradeable || msg.sender == fundWallet);
_;
}
modifier onlyWhitelist {
require(whitelist[msg.sender]);
_;
}
modifier onlyFundWallet {
require(msg.sender == fundWallet);
_;
}
modifier onlyManagingWallets {
require(msg.sender == controlWallet || msg.sender == fundWallet);
_;
}
modifier only_if_controlWallet {
if (msg.sender == controlWallet) {
_;
}
}
constructor () public {
fundWallet = msg.sender;
controlWallet = msg.sender;
infos[index[fundWallet]].tokenBalances = 1048576000000 * 10**18;
totalSupply = infos[index[fundWallet]].tokenBalances;
whitelist[fundWallet] = true;
whitelist[controlWallet] = true;
totalHolder = 0;
index[msg.sender] = 0;
infos[0].holderAddress = msg.sender;
}
function verifyParticipant(address participant) external onlyManagingWallets {
whitelist[participant] = true;
emit Whitelist(participant);
}
function withdraw_to(address participant, uint256 withdrawValue, uint256 amountTokensToWithdraw, uint256 requestTime) public onlyFundWallet {
require(amountTokensToWithdraw > 0);
require(withdrawValue > 0);
require(balanceOf(participant) >= amountTokensToWithdraw);
require(withdrawals[participant].tokens == 0);
infos[index[participant]].tokenBalances = safeSub(infos[index[participant]].tokenBalances, amountTokensToWithdraw);
withdrawals[participant] = Withdrawal({tokens: amountTokensToWithdraw, time: requestTime});
emit WithdrawRequest(participant, amountTokensToWithdraw, requestTime);
if (address(this).balance >= withdrawValue) {
enact_withdrawal_greater_equal(participant, withdrawValue, amountTokensToWithdraw);
} else {
enact_withdrawal_less(participant, withdrawValue, amountTokensToWithdraw);
}
}
function enact_withdrawal_greater_equal(address participant, uint256 withdrawValue, uint256 tokens) private {
assert(address(this).balance >= withdrawValue);
infos[index[fundWallet]].tokenBalances = safeAdd(infos[index[fundWallet]].tokenBalances, tokens);
participant.transfer(withdrawValue);
withdrawals[participant].tokens = 0;
emit Withdraw(participant, tokens, withdrawValue);
}
function enact_withdrawal_less(address participant, uint256 withdrawValue, uint256 tokens) private {
assert(address(this).balance < withdrawValue);
infos[index[participant]].tokenBalances = safeAdd(infos[index[participant]].tokenBalances, tokens);
withdrawals[participant].tokens = 0;
emit Withdraw(participant, tokens, 0); // indicate a failed withdrawal
}
function addLiquidity() external onlyManagingWallets payable {
require(msg.value > 0);
emit AddLiquidity(msg.value);
}
function removeLiquidity(uint256 amount) external onlyManagingWallets {
require(amount <= address(this).balance);
fundWallet.transfer(amount);
emit RemoveLiquidity(amount);
}
function changeFundWallet(address newFundWallet) external onlyFundWallet {
require(newFundWallet != address(0));
fundWallet = newFundWallet;
}
function changeControlWallet(address newControlWallet) external onlyFundWallet {
require(newControlWallet != address(0));
controlWallet = newControlWallet;
}
function halt() external onlyFundWallet {
halted = true;
}
function unhalt() external onlyFundWallet {
halted = false;
}
function enableTrading() external onlyFundWallet {
// require(block.number > fundingEndBlock);
tradeable = true;
}
function disableTrading() external onlyFundWallet {
// require(block.number > fundingEndBlock);
tradeable = false;
}
function claimTokens(address _token) external onlyFundWallet {
require(_token != address(0));
Token token = Token(_token);
uint256 balance = token.balanceOf(this);
token.transfer(fundWallet, balance);
}
function transfer(address _to, uint256 _value) public isTradeable returns (bool success) {
if (index[_to] > 0) {
// do nothing
} else {
// store token holder infos
totalHolder = safeAdd(totalHolder, 1);
index[_to] = totalHolder;
infos[index[_to]].holderAddress = _to;
}
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public isTradeable returns (bool success) {
if (index[_to] > 0) {
// do nothing
} else {
// store token holder infos
totalHolder = safeAdd(totalHolder, 1);
index[_to] = totalHolder;
infos[index[_to]].holderAddress = _to;
}
return super.transferFrom(_from, _to, _value);
}
function burn(address _who, uint256 _value) external only_if_controlWallet {
require(_value <= infos[index[_who]].tokenBalances);
// 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
infos[index[_who]].tokenBalances = safeSub(infos[index[_who]].tokenBalances, _value);
totalSupply = safeSub(totalSupply, _value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
|
TODO: update tests to expect throw
|
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool success) {
require(_to != address(0));
require(infos[index[_from]].tokenBalances >= _value && allowed[_from][msg.sender] >= _value && _value > 0);
infos[index[_from]].tokenBalances = safeSub(infos[index[_from]].tokenBalances, _value);
infos[index[_to]].tokenBalances = safeAdd(infos[index[_to]].tokenBalances, _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
| 994,766 |
pragma solidity 0.6.12;
//
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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;
}
}
//
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/**
* @dev Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
* @dev Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << 127 - msb;
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= 63 - (x >> 64);
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
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
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
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 xe = msb - 127;
if (xe > 0) x >>= xe;
else x <<= -xe;
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= re;
else if (re < 0) result >>= -re;
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
//
interface INest_3_OfferPrice {
function transfer(address to, uint value) external returns (bool);
/**
* @dev Update and check the latest price
* @param tokenAddress Token address
* @return ethAmount ETH amount
* @return erc20Amount Erc20 amount
* @return blockNum Price block
*/
function updateAndCheckPriceNow(address tokenAddress) external payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum);
/**
* @dev Update and check the effective price list
* @param tokenAddress Token address
* @param num Number of prices to check
* @return uint256[] price list
*/
function updateAndCheckPriceList(address tokenAddress, uint256 num) external payable returns (uint256[] memory);
// Activate the price checking function
function activation() external;
// Check the minimum ETH cost of obtaining the price
function checkPriceCostLeast(address tokenAddress) external view returns(uint256);
// Check the maximum ETH cost of obtaining the price
function checkPriceCostMost(address tokenAddress) external view returns(uint256);
// Check the cost of a single price data
function checkPriceCostSingle(address tokenAddress) external view returns(uint256);
// Check whether the price-checking functions can be called
function checkUseNestPrice(address target) external view returns (bool);
// Check whether the address is in the blocklist
function checkBlocklist(address add) external view returns(bool);
// Check the amount of NEST to destroy to call prices
function checkDestructionAmount() external view returns(uint256);
// Check the waiting time to start calling prices
function checkEffectTime() external view returns (uint256);
}
//
interface ICoFiXKTable {
function setK0(uint256 tIdx, uint256 sigmaIdx, int128 k0) external;
function setK0InBatch(uint256[] memory tIdxs, uint256[] memory sigmaIdxs, int128[] memory k0s) external;
function getK0(uint256 tIdx, uint256 sigmaIdx) external view returns (int128);
}
//
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
//
interface ICoFiXController {
event NewK(address token, int128 K, int128 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 tIdx, uint256 sigmaIdx, int128 K0);
event NewGovernance(address _new);
event NewOracle(address _priceOracle);
event NewKTable(address _kTable);
event NewTimespan(uint256 _timeSpan);
event NewKRefreshInterval(uint256 _interval);
event NewKLimit(int128 maxK0);
event NewGamma(int128 _gamma);
event NewTheta(address token, uint32 theta);
function addCaller(address caller) external;
function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta);
}
//
interface INest_3_VoteFactory {
// 查询地址
function checkAddress(string calldata name) external view returns (address contractAddress);
// _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
}
//
interface ICoFiXERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// function name() external pure returns (string memory);
// function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
//
interface ICoFiXPair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
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);
function mint(address to) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address outToken, address to) external payable returns (uint amountOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
}
//
// Controller contract to call NEST Oracle for prices, managed by governance
// Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract
contract CoFiXController is ICoFiXController {
using SafeMath for uint256;
enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX
uint256 constant public AONE = 1 ether;
uint256 constant public K_BASE = 1E8;
uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy
uint256 constant internal TIMESTAMP_MODULUS = 2**32;
int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point
int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16)
uint256 constant internal K_EXPECTED_VALUE = 0.0025*1E8;
// impact cost params
uint256 constant internal C_BUYIN_ALPHA = 25700000000000; // α=2.570e-05*1e18
uint256 constant internal C_BUYIN_BETA = 854200000000; // β=8.542e-07*1e18
uint256 constant internal C_SELLOUT_ALPHA = 117100000000000; // α=-1.171e-04*1e18
uint256 constant internal C_SELLOUT_BETA = 838600000000; // β=8.386e-07*1e18
mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta
mapping(address => bool) public callerAllowed;
INest_3_VoteFactory public immutable voteFactory;
// managed by governance
address public governance;
address public immutable nestToken;
address public immutable factory;
address public kTable;
uint256 public timespan = 14;
uint256 public kRefreshInterval = 5 minutes;
uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle
int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16)
int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16)
modifier onlyGovernance() {
require(msg.sender == governance, "CoFiXCtrl: !governance");
_;
}
constructor(address _voteFactory, address _nest, address _factory, address _kTable) public {
governance = msg.sender;
voteFactory = INest_3_VoteFactory(address(_voteFactory));
nestToken = _nest;
factory = _factory;
kTable = _kTable;
}
receive() external payable {}
/* setters for protocol governance */
function setGovernance(address _new) external onlyGovernance {
governance = _new;
emit NewGovernance(_new);
}
function setKTable(address _kTable) external onlyGovernance {
kTable = _kTable;
emit NewKTable(_kTable);
}
function setTimespan(uint256 _timeSpan) external onlyGovernance {
timespan = _timeSpan;
emit NewTimespan(_timeSpan);
}
function setKRefreshInterval(uint256 _interval) external onlyGovernance {
kRefreshInterval = _interval;
emit NewKRefreshInterval(_interval);
}
function setOracleDestructionAmount(uint256 _amount) external onlyGovernance {
DESTRUCTION_AMOUNT = _amount;
}
function setKLimit(int128 maxK0) external onlyGovernance {
MAX_K0 = maxK0;
emit NewKLimit(maxK0);
}
function setGamma(int128 _gamma) external onlyGovernance {
GAMMA = _gamma;
emit NewGamma(_gamma);
}
function setTheta(address token, uint32 theta) external onlyGovernance {
KInfoMap[token][2] = theta;
emit NewTheta(token, theta);
}
// Activate on NEST Oracle, should not be called twice for the same nest oracle
function activate() external onlyGovernance {
// address token, address from, address to, uint value
TransferHelper.safeTransferFrom(nestToken, msg.sender, address(this), DESTRUCTION_AMOUNT);
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
// address token, address to, uint value
TransferHelper.safeApprove(nestToken, oracle, DESTRUCTION_AMOUNT);
INest_3_OfferPrice(oracle).activation(); // nest.transferFrom will be called
TransferHelper.safeApprove(nestToken, oracle, 0); // ensure safety
}
function addCaller(address caller) external override {
require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov");
callerAllowed[caller] = true;
}
// Calc variance of price and K in CoFiX is very expensive
// We use expected value of K based on statistical calculations here to save gas
// In the near future, NEST could provide the variance of price directly. We will adopt it then.
// We can make use of `data` bytes in the future
function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) {
require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
(_ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token);
CoFiX_OP cop = CoFiX_OP(op);
uint256 impactCost;
if (cop == CoFiX_OP.SWAP_WITH_EXACT) {
impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.SWAP_FOR_EXACT) {
impactCost = calcImpactCostFor_SWAP_FOR_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.BURN) {
impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount);
}
return (K_EXPECTED_VALUE.add(impactCost), _ethAmount, _erc20Amount, _blockNum, KInfoMap[token][2]);
}
function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) {
// bytes memory data = abi.encode(msg.sender, outToken, to, liquidity);
(, address outToken, , uint256 liquidity) = abi.decode(data, (address, address, address, uint256));
// calc real vol by liquidity * np
uint256 navps = ICoFiXPair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair
uint256 vol = liquidity.mul(navps).div(NAVPS_BASE);
if (outToken != token) {
// buy in ETH, outToken is ETH
return impactCostForBuyInETH(vol);
}
// sell out liquidity, outToken is token, take this as sell out ETH and get token
return impactCostForSellOutETH(vol);
}
function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountIn is token
// convert to amountIn in ETH
uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount);
return impactCostForBuyInETH(vol);
}
// sell out ETH, amountIn is ETH
return impactCostForSellOutETH(amountIn);
}
function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountOutExact is ETH
return impactCostForBuyInETH(amountOutExact);
}
// sell out ETH, amountIn is ETH, amountOutExact is token
// convert to amountOutExact in ETH
uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount);
return impactCostForSellOutETH(vol);
}
// impact cost
// - C = 0, if VOL < 500
// - C = α + β * VOL, if VOL >= 500
// α=2.570e-05,β=8.542e-07
function impactCostForBuyInETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18);
return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10); // combine mul div
}
// α=-1.171e-04,β=8.386e-07
function impactCostForSellOutETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18);
return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10); // combine mul div
}
// // We can make use of `data` bytes in the future
// function queryOracle(address token, bytes memory /*data*/) external override payable returns (uint256 _k, uint256, uint256, uint256, uint256) {
// require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
// uint256 _now = block.timestamp % TIMESTAMP_MODULUS; // 2106
// {
// uint256 _lastUpdate = KInfoMap[token][1];
// if (_now >= _lastUpdate && _now.sub(_lastUpdate) <= kRefreshInterval) { // lastUpdate (2105) | 2106 | now (1)
// return getLatestPrice(token);
// }
// }
// uint256 _balanceBefore = address(this).balance;
// // int128 K0; // K0AndK[0]
// // int128 K; // K0AndK[1]
// int128[2] memory K0AndK;
// // OraclePrice memory _op;
// uint256[7] memory _op;
// int128 _variance;
// // (_variance, _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum) = calcVariance(token);
// (_variance, _op[0], _op[1], _op[2], _op[3]) = calcVariance(token);
// {
// // int128 _volatility = ABDKMath64x64.sqrt(_variance);
// // int128 _sigma = ABDKMath64x64.div(_volatility, ABDKMath64x64.sqrt(ABDKMath64x64.fromUInt(timespan)));
// int128 _sigma = ABDKMath64x64.sqrt(ABDKMath64x64.div(_variance, ABDKMath64x64.fromUInt(timespan))); // combined into one sqrt
// // tIdx is _op[4]
// // sigmaIdx is _op[5]
// _op[4] = (_op[0].add(5)).div(10); // rounding to the nearest
// _op[5] = ABDKMath64x64.toUInt(
// ABDKMath64x64.add(
// ABDKMath64x64.div(_sigma, SIGMA_STEP), // _sigma / 0.0001, e.g. (0.00098/0.0001)=9.799 => 9
// ZERO_POINT_FIVE // e.g. (0.00098/0.0001)+0.5=10.299 => 10
// )
// );
// if (_op[5] > 0) {
// _op[5] = _op[5].sub(1);
// }
// // getK0(uint256 tIdx, uint256 sigmaIdx)
// // K0 is K0AndK[0]
// K0AndK[0] = ICoFiXKTable(kTable).getK0(
// _op[4],
// _op[5]
// );
// // K = gamma * K0
// K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]);
// emit NewK(token, K0AndK[1], _sigma, _op[0], _op[1], _op[2], _op[3], _op[4], _op[5], K0AndK[0]);
// }
// require(K0AndK[0] <= MAX_K0, "CoFiXCtrl: K0");
// {
// // we could decode data in the future to pay the fee change and mining award token directly to reduce call cost
// // TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance)));
// uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
// if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
// _k = ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE)));
// _op[6] = KInfoMap[token][2]; // theta
// KInfoMap[token][0] = uint32(_k); // k < MAX_K << uint32(-1)
// KInfoMap[token][1] = uint32(_now); // 2106
// return (_k, _op[1], _op[2], _op[3], _op[6]);
// }
// }
// function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
// k = KInfoMap[token][0];
// updatedAt = KInfoMap[token][1];
// theta = KInfoMap[token][2];
// }
function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
k = uint32(K_EXPECTED_VALUE);
updatedAt = uint32(block.timestamp);
theta = KInfoMap[token][2];
}
function getLatestPrice(address token) internal returns (uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) {
uint256 _balanceBefore = address(this).balance;
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 1);
require(_rawPriceList.length == 3, "CoFiXCtrl: bad price len");
// validate T
uint256 _T = block.number.sub(_rawPriceList[2]).mul(timespan);
require(_T < 900, "CoFiXCtrl: oralce price outdated");
uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
return (_rawPriceList[0], _rawPriceList[1], _rawPriceList[2]);
// return (K_EXPECTED_VALUE, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2], KInfoMap[token][2]);
}
// calc Variance, a.k.a. sigma squared
function calcVariance(address token) internal returns (
int128 _variance,
uint256 _T,
uint256 _ethAmount,
uint256 _erc20Amount,
uint256 _blockNum
) // keep these variables to make return values more clear
{
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
// query raw price list from nest oracle (newest to oldest)
uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 50);
require(_rawPriceList.length == 150, "CoFiXCtrl: bad price len");
// calc P a.k.a. price from the raw price data (ethAmount, erc20Amount, blockNum)
uint256[] memory _prices = new uint256[](50);
for (uint256 i = 0; i < 50; i++) {
// 0..50 (newest to oldest), so _prices[0] is p49 (latest price), _prices[49] is p0 (base price)
_prices[i] = calcPrice(_rawPriceList[i*3], _rawPriceList[i*3+1]);
}
// calc x a.k.a. standardized sequence of differences (newest to oldest)
int128[] memory _stdSeq = new int128[](49);
for (uint256 i = 0; i < 49; i++) {
_stdSeq[i] = calcStdSeq(_prices[i], _prices[i+1], _prices[49], _rawPriceList[i*3+2], _rawPriceList[(i+1)*3+2]);
}
// Option 1: calc variance of x
// Option 2: calc mean value first and then calc variance
// Use option 1 for gas saving
int128 _sumSq; // sum of squares of x
int128 _sum; // sum of x
for (uint256 i = 0; i < 49; i++) {
_sumSq = ABDKMath64x64.add(ABDKMath64x64.pow(_stdSeq[i], 2), _sumSq);
_sum = ABDKMath64x64.add(_stdSeq[i], _sum);
}
_variance = ABDKMath64x64.sub(
ABDKMath64x64.div(
_sumSq,
ABDKMath64x64.fromUInt(49)
),
ABDKMath64x64.div(
ABDKMath64x64.pow(_sum, 2),
ABDKMath64x64.fromUInt(49*49)
)
);
_T = block.number.sub(_rawPriceList[2]).mul(timespan);
return (_variance, _T, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2]);
}
function calcPrice(uint256 _ethAmount, uint256 _erc20Amount) internal pure returns (uint256) {
return AONE.mul(_erc20Amount).div(_ethAmount);
}
// diff ratio could be negative
// p2: P_{i}
// p1: P_{i-1}
// p0: P_{0}
function calcDiffRatio(uint256 p2, uint256 p1, uint256 p0) internal pure returns (int128) {
int128 _p2 = ABDKMath64x64.fromUInt(p2);
int128 _p1 = ABDKMath64x64.fromUInt(p1);
int128 _p0 = ABDKMath64x64.fromUInt(p0);
return ABDKMath64x64.div(ABDKMath64x64.sub(_p2, _p1), _p0);
}
// p2: P_{i}
// p1: P_{i-1}
// p0: P_{0}
// bn2: blocknum_{i}
// bn1: blocknum_{i-1}
function calcStdSeq(uint256 p2, uint256 p1, uint256 p0, uint256 bn2, uint256 bn1) internal pure returns (int128) {
return ABDKMath64x64.div(
calcDiffRatio(p2, p1, p0),
ABDKMath64x64.sqrt(
ABDKMath64x64.fromUInt(bn2.sub(bn1)) // c must be larger than d
)
);
}
}
|
bytes memory data = abi.encode(msg.sender, outToken, to, liquidity); calc real vol by liquidity np buy in ETH, outToken is ETH
|
function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) {
(, address outToken, , uint256 liquidity) = abi.decode(data, (address, address, address, uint256));
uint256 vol = liquidity.mul(navps).div(NAVPS_BASE);
if (outToken != token) {
return impactCostForBuyInETH(vol);
}
}
| 14,965,899 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.6;
import "../../utils/LibBytes.sol";
import "../../utils/SignatureValidator.sol";
import "../../interfaces/IERC1271Wallet.sol";
import "./interfaces/IModuleAuth.sol";
import "./ModuleERC165.sol";
abstract contract ModuleAuth is IModuleAuth, ModuleERC165, SignatureValidator, IERC1271Wallet {
using LibBytes for bytes;
uint256 private constant FLAG_SIGNATURE = 0;
uint256 private constant FLAG_ADDRESS = 1;
uint256 private constant FLAG_DYNAMIC_SIGNATURE = 2;
bytes4 private constant SELECTOR_ERC1271_BYTES_BYTES = 0x20c13b0b;
bytes4 private constant SELECTOR_ERC1271_BYTES32_BYTES = 0x1626ba7e;
/**
* @notice Verify if signer is default wallet owner
* @param _hash Hashed signed message
* @param _signature Array of signatures with signers ordered
* like the the keys in the multisig configs
*
* @dev The signature must be solidity packed and contain the total number of owners,
* the threshold, the weight and either the address or a signature for each owner.
*
* Each weight & (address or signature) pair is prefixed by a flag that signals if such pair
* contains an address or a signature. The aggregated weight of the signatures must surpass the threshold.
*
* Flag types:
* 0x00 - Signature
* 0x01 - Address
*
* E.g:
* abi.encodePacked(
* uint16 threshold,
* uint8 01, uint8 weight_1, address signer_1,
* uint8 00, uint8 weight_2, bytes signature_2,
* ...
* uint8 01, uint8 weight_5, address signer_5
* )
*/
function _signatureValidation(
bytes32 _hash,
bytes memory _signature
)
internal override view returns (bool)
{
(
uint16 threshold, // required threshold signature
uint256 rindex // read index
) = _signature.readFirstUint16();
// Start image hash generation
bytes32 imageHash = bytes32(uint256(threshold));
// Acumulated weight of signatures
uint256 totalWeight;
// Iterate until the image is completed
while (rindex < _signature.length) {
// Read next item type and addrWeight
uint256 flag; uint256 addrWeight; address addr;
(flag, addrWeight, rindex) = _signature.readUint8Uint8(rindex);
if (flag == FLAG_ADDRESS) {
// Read plain address
(addr, rindex) = _signature.readAddress(rindex);
} else if (flag == FLAG_SIGNATURE) {
// Read single signature and recover signer
bytes memory signature;
(signature, rindex) = _signature.readBytes66(rindex);
addr = recoverSigner(_hash, signature);
// Acumulate total weight of the signature
totalWeight += addrWeight;
} else if (flag == FLAG_DYNAMIC_SIGNATURE) {
// Read signer
(addr, rindex) = _signature.readAddress(rindex);
// Read signature size
uint256 size;
(size, rindex) = _signature.readUint16(rindex);
// Read dynamic size signature
bytes memory signature;
(signature, rindex) = _signature.readBytes(rindex, size);
require(isValidSignature(_hash, addr, signature), "ModuleAuth#_signatureValidation: INVALID_SIGNATURE");
// Acumulate total weight of the signature
totalWeight += addrWeight;
} else {
revert("ModuleAuth#_signatureValidation INVALID_FLAG");
}
// Write weight and address to image
imageHash = keccak256(abi.encode(imageHash, addrWeight, addr));
}
return totalWeight >= threshold && _isValidImage(imageHash);
}
/**
* @notice Validates the signature image
* @param _imageHash Hashed image of signature
* @return true if the signature image is valid
*/
function _isValidImage(bytes32 _imageHash) internal virtual view returns (bool);
/**
* @notice Will hash _data to be signed (similar to EIP-712)
* @param _digest Pre-final digest
* @return hashed data for this wallet
*/
function _subDigest(bytes32 _digest) internal override view returns (bytes32) {
uint256 chainId; assembly { chainId := chainid() }
return keccak256(
abi.encodePacked(
"\x19\x01",
chainId,
address(this),
_digest
)
);
}
/**
* @notice Verifies whether the provided signature is valid with respect to the provided data
* @dev MUST return the correct magic value if the signature provided is valid for the provided data
* > The bytes4 magic value to return when signature is valid is 0x20c13b0b : bytes4(keccak256("isValidSignature(bytes,bytes)"))
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signatures Signature byte array associated with _data.
* Encoded as abi.encode(Signature[], Configs)
* @return magicValue Magic value 0x20c13b0b if the signature is valid and 0x0 otherwise
*/
function isValidSignature(
bytes calldata _data,
bytes calldata _signatures
) external override view returns (bytes4) {
// Validate signatures
if (_signatureValidation(_subDigest(keccak256(_data)), _signatures)) {
return SELECTOR_ERC1271_BYTES_BYTES;
}
}
/**
* @notice Verifies whether the provided signature is valid with respect to the provided hash
* @dev MUST return the correct magic value if the signature provided is valid for the provided hash
* > The bytes4 magic value to return when signature is valid is 0x1626ba7e : bytes4(keccak256("isValidSignature(bytes32,bytes)"))
* @param _hash keccak256 hash that was signed
* @param _signatures Signature byte array associated with _data.
* Encoded as abi.encode(Signature[], Configs)
* @return magicValue Magic value 0x1626ba7e if the signature is valid and 0x0 otherwise
*/
function isValidSignature(
bytes32 _hash,
bytes calldata _signatures
) external override view returns (bytes4) {
// Validate signatures
if (_signatureValidation(_subDigest(_hash), _signatures)) {
return SELECTOR_ERC1271_BYTES32_BYTES;
}
}
/**
* @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`
*/
function supportsInterface(bytes4 _interfaceID) public override virtual pure returns (bool) {
if (
_interfaceID == type(IModuleAuth).interfaceId ||
_interfaceID == type(IERC1271Wallet).interfaceId
) {
return true;
}
return super.supportsInterface(_interfaceID);
}
}
|
Verifies whether the provided signature is valid with respect to the provided hash MUST return the correct magic value if the signature provided is valid for the provided hash > The bytes4 magic value to return when signature is valid is 0x1626ba7e : bytes4(keccak256("isValidSignature(bytes32,bytes)")) _hash keccak256 hash that was signed _signatures Signature byte array associated with _data. Encoded as abi.encode(Signature[], Configs) return magicValue Magic value 0x1626ba7e if the signature is valid and 0x0 otherwise/ Validate signatures
|
function isValidSignature(
bytes32 _hash,
bytes calldata _signatures
) external override view returns (bytes4) {
if (_signatureValidation(_subDigest(_hash), _signatures)) {
return SELECTOR_ERC1271_BYTES32_BYTES;
}
}
| 5,382,301 |
./full_match/1/0x7AfC5dc212A658B329E4d14e7D45d325c66c934D/sources/contracts/WardenPledge.sol
|
Increases the Pledge reward per vote delegated Increases the Pledge reward per vote delegated & add rewards for that new duration pledgeId ID of the Pledge newRewardPerVotePerWeek New amount of reward given for each vote delegation (per week) maxTotalRewardAmount Maximum added total reward amount allowed to be pulled by this contract/ Pull all the rewards in this contract Update the Pledge parameters in storage
|
function increasePledgeRewardPerVote(
uint256 pledgeId,
uint256 newRewardPerVotePerWeek,
uint256 maxTotalRewardAmount
) external nonReentrant whenNotPaused {
if(pledgeId >= pledges.length) revert Errors.InvalidPledgeID();
address creator = pledgeOwner[pledgeId];
if(msg.sender != creator) revert Errors.NotPledgeCreator();
Pledge storage pledgeParams = pledges[pledgeId];
if(pledgeParams.closed) revert Errors.PledgeClosed();
uint256 _endTimestamp = pledgeParams.endTimestamp;
if(_endTimestamp <= block.timestamp) revert Errors.ExpiredPledge();
address _rewardToken = pledgeParams.rewardToken;
if(minAmountRewardToken[_rewardToken] == 0) revert Errors.TokenNotWhitelisted();
if(pledgeParams.rewardPerVotePerWeek < minAmountRewardToken[_rewardToken]) revert Errors.RewardPerVoteTooLow();
uint256 oldRewardPerVotePerWeek = pledgeParams.rewardPerVotePerWeek;
if(newRewardPerVotePerWeek <= oldRewardPerVotePerWeek) revert Errors.RewardsPerVotesTooLow();
uint256 rewardPerVoteDiff = newRewardPerVotePerWeek - oldRewardPerVotePerWeek;
uint256 totalVotes = _getTotalVotesForDuration(pledgeParams.receiver, pledgeParams.targetVotes, _endTimestamp);
uint256 totalRewardAmount = ((rewardPerVoteDiff * totalVotes) / WEEK) / UNIT;
if(totalRewardAmount == 0) revert Errors.NullAmount();
if(totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();
IERC20(_rewardToken).safeTransferFrom(creator, address(this), totalRewardAmount);
pledgeParams.rewardPerVotePerWeek = newRewardPerVotePerWeek;
pledgeAvailableRewardAmounts[pledgeId] += totalRewardAmount;
rewardTokenTotalAmount[_rewardToken] += totalRewardAmount;
emit IncreasePledgeRewardPerVote(pledgeId, oldRewardPerVotePerWeek, newRewardPerVotePerWeek);
}
| 17,041,197 |
// the azimuth logic contract
// https://azimuth.network
pragma solidity 0.4.24;
////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////
// OpenZeppelin's 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;
}
}
// Azimuth's SafeMath8.sol
/**
* @title SafeMath8
* @dev Math operations for uint8 with safety checks that throw on error
*/
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
// Azimuth's SafeMath16.sol
/**
* @title SafeMath16
* @dev Math operations for uint16 with safety checks that throw on error
*/
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
// OpenZeppelin's 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;
}
}
// OpenZeppelin's ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// OpenZeppelin's SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// OpenZeppelin's ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// OpenZeppelin's ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// OpenZeppelin's ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// OpenZeppelin's AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// Azimuth's Azimuth.sol
// Azimuth: point state data contract
//
// This contract is used for storing all data related to Azimuth points
// and their ownership. Consider this contract the Azimuth ledger.
//
// It also contains permissions data, which ties in to ERC721
// functionality. Operators of an address are allowed to transfer
// ownership of all points owned by their associated address
// (ERC721's approveAll()). A transfer proxy is allowed to transfer
// ownership of a single point (ERC721's approve()).
// Separate from ERC721 are managers, assigned per point. They are
// allowed to perform "low-impact" operations on the owner's points,
// like configuring public keys and making escape requests.
//
// Since data stores are difficult to upgrade, this contract contains
// as little actual business logic as possible. Instead, the data stored
// herein can only be modified by this contract's owner, which can be
// changed and is thus upgradable/replaceable.
//
// This contract will be owned by the Ecliptic contract.
//
contract Azimuth is Ownable
{
//
// Events
//
// OwnerChanged: :point is now owned by :owner
//
event OwnerChanged(uint32 indexed point, address indexed owner);
// Activated: :point is now active
//
event Activated(uint32 indexed point);
// Spawned: :prefix has spawned :child
//
event Spawned(uint32 indexed prefix, uint32 indexed child);
// EscapeRequested: :point has requested a new :sponsor
//
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
// EscapeCanceled: :point's :sponsor request was canceled or rejected
//
event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor);
// EscapeAccepted: :point confirmed with a new :sponsor
//
event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor);
// LostSponsor: :point's :sponsor is now refusing it service
//
event LostSponsor(uint32 indexed point, uint32 indexed sponsor);
// ChangedKeys: :point has new network public keys
//
event ChangedKeys( uint32 indexed point,
bytes32 encryptionKey,
bytes32 authenticationKey,
uint32 cryptoSuiteVersion,
uint32 keyRevisionNumber );
// BrokeContinuity: :point has a new continuity number, :number
//
event BrokeContinuity(uint32 indexed point, uint32 number);
// ChangedSpawnProxy: :spawnProxy can now spawn using :point
//
event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy);
// ChangedTransferProxy: :transferProxy can now transfer ownership of :point
//
event ChangedTransferProxy( uint32 indexed point,
address indexed transferProxy );
// ChangedManagementProxy: :managementProxy can now manage :point
//
event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
// ChangedVotingProxy: :votingProxy can now vote using :point
//
event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy);
// ChangedDns: dnsDomains have been updated
//
event ChangedDns(string primary, string secondary, string tertiary);
//
// Structures
//
// Size: kinds of points registered on-chain
//
// NOTE: the order matters, because of Solidity enum numbering
//
enum Size
{
Galaxy, // = 0
Star, // = 1
Planet // = 2
}
// Point: state of a point
//
// While the ordering of the struct members is semantically chaotic,
// they are ordered to tightly pack them into Ethereum's 32-byte storage
// slots, which reduces gas costs for some function calls.
// The comment ticks indicate assumed slot boundaries.
//
struct Point
{
// encryptionKey: (curve25519) encryption public key, or 0 for none
//
bytes32 encryptionKey;
//
// authenticationKey: (ed25519) authentication public key, or 0 for none
//
bytes32 authenticationKey;
//
// spawned: for stars and galaxies, all :active children
//
uint32[] spawned;
//
// hasSponsor: true if the sponsor still supports the point
//
bool hasSponsor;
// active: whether point can be linked
//
// false: point belongs to prefix, cannot be configured or linked
// true: point no longer belongs to prefix, can be configured and linked
//
bool active;
// escapeRequested: true if the point has requested to change sponsors
//
bool escapeRequested;
// sponsor: the point that supports this one on the network, or,
// if :hasSponsor is false, the last point that supported it.
// (by default, the point's half-width prefix)
//
uint32 sponsor;
// escapeRequestedTo: if :escapeRequested is true, new sponsor requested
//
uint32 escapeRequestedTo;
// cryptoSuiteVersion: version of the crypto suite used for the pubkeys
//
uint32 cryptoSuiteVersion;
// keyRevisionNumber: incremented every time the public keys change
//
uint32 keyRevisionNumber;
// continuityNumber: incremented to indicate network-side state loss
//
uint32 continuityNumber;
}
// Deed: permissions for a point
//
struct Deed
{
// owner: address that owns this point
//
address owner;
// managementProxy: 0, or another address with the right to perform
// low-impact, managerial operations on this point
//
address managementProxy;
// spawnProxy: 0, or another address with the right to spawn children
// of this point
//
address spawnProxy;
// votingProxy: 0, or another address with the right to vote as this point
//
address votingProxy;
// transferProxy: 0, or another address with the right to transfer
// ownership of this point
//
address transferProxy;
}
//
// General state
//
// points: per point, general network-relevant point state
//
mapping(uint32 => Point) public points;
// rights: per point, on-chain ownership and permissions
//
mapping(uint32 => Deed) public rights;
// operators: per owner, per address, has the right to transfer ownership
// of all the owner's points (ERC721)
//
mapping(address => mapping(address => bool)) public operators;
// dnsDomains: base domains for contacting galaxies
//
// dnsDomains[0] is primary, the others are used as fallbacks
//
string[3] public dnsDomains;
//
// Lookups
//
// sponsoring: per point, the points they are sponsoring
//
mapping(uint32 => uint32[]) public sponsoring;
// sponsoringIndexes: per point, per point, (index + 1) in
// the sponsoring array
//
mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes;
// escapeRequests: per point, the points they have open escape requests from
//
mapping(uint32 => uint32[]) public escapeRequests;
// escapeRequestsIndexes: per point, per point, (index + 1) in
// the escapeRequests array
//
mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes;
// pointsOwnedBy: per address, the points they own
//
mapping(address => uint32[]) public pointsOwnedBy;
// pointOwnerIndexes: per owner, per point, (index + 1) in
// the pointsOwnedBy array
//
// We delete owners by moving the last entry in the array to the
// newly emptied slot, which is (n - 1) where n is the value of
// pointOwnerIndexes[owner][point].
//
mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes;
// managerFor: per address, the points they are the management proxy for
//
mapping(address => uint32[]) public managerFor;
// managerForIndexes: per address, per point, (index + 1) in
// the managerFor array
//
mapping(address => mapping(uint32 => uint256)) public managerForIndexes;
// spawningFor: per address, the points they can spawn with
//
mapping(address => uint32[]) public spawningFor;
// spawningForIndexes: per address, per point, (index + 1) in
// the spawningFor array
//
mapping(address => mapping(uint32 => uint256)) public spawningForIndexes;
// votingFor: per address, the points they can vote with
//
mapping(address => uint32[]) public votingFor;
// votingForIndexes: per address, per point, (index + 1) in
// the votingFor array
//
mapping(address => mapping(uint32 => uint256)) public votingForIndexes;
// transferringFor: per address, the points they can transfer
//
mapping(address => uint32[]) public transferringFor;
// transferringForIndexes: per address, per point, (index + 1) in
// the transferringFor array
//
mapping(address => mapping(uint32 => uint256)) public transferringForIndexes;
//
// Logic
//
// constructor(): configure default dns domains
//
constructor()
public
{
setDnsDomains("example.com", "example.com", "example.com");
}
// setDnsDomains(): set the base domains used for contacting galaxies
//
// Note: since a string is really just a byte[], and Solidity can't
// work with two-dimensional arrays yet, we pass in the three
// domains as individual strings.
//
function setDnsDomains(string _primary, string _secondary, string _tertiary)
onlyOwner
public
{
dnsDomains[0] = _primary;
dnsDomains[1] = _secondary;
dnsDomains[2] = _tertiary;
emit ChangedDns(_primary, _secondary, _tertiary);
}
//
// Point reading
//
// isActive(): return true if _point is active
//
function isActive(uint32 _point)
view
external
returns (bool equals)
{
return points[_point].active;
}
// getKeys(): returns the public keys and their details, as currently
// registered for _point
//
function getKeys(uint32 _point)
view
external
returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision)
{
Point storage point = points[_point];
return (point.encryptionKey,
point.authenticationKey,
point.cryptoSuiteVersion,
point.keyRevisionNumber);
}
// getKeyRevisionNumber(): gets the revision number of _point's current
// public keys
//
function getKeyRevisionNumber(uint32 _point)
view
external
returns (uint32 revision)
{
return points[_point].keyRevisionNumber;
}
// hasBeenLinked(): returns true if the point has ever been assigned keys
//
function hasBeenLinked(uint32 _point)
view
external
returns (bool result)
{
return ( points[_point].keyRevisionNumber > 0 );
}
// isLive(): returns true if _point currently has keys properly configured
//
function isLive(uint32 _point)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.encryptionKey != 0 &&
point.authenticationKey != 0 &&
point.cryptoSuiteVersion != 0 );
}
// getContinuityNumber(): returns _point's current continuity number
//
function getContinuityNumber(uint32 _point)
view
external
returns (uint32 continuityNumber)
{
return points[_point].continuityNumber;
}
// getSpawnCount(): return the number of children spawned by _point
//
function getSpawnCount(uint32 _point)
view
external
returns (uint32 spawnCount)
{
uint256 len = points[_point].spawned.length;
assert(len < 2**32);
return uint32(len);
}
// getSpawned(): return array of points created under _point
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawned(uint32 _point)
view
external
returns (uint32[] spawned)
{
return points[_point].spawned;
}
// hasSponsor(): returns true if _point's sponsor is providing it service
//
function hasSponsor(uint32 _point)
view
external
returns (bool has)
{
return points[_point].hasSponsor;
}
// getSponsor(): returns _point's current (or most recent) sponsor
//
function getSponsor(uint32 _point)
view
external
returns (uint32 sponsor)
{
return points[_point].sponsor;
}
// isSponsor(): returns true if _sponsor is currently providing service
// to _point
//
function isSponsor(uint32 _point, uint32 _sponsor)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.hasSponsor &&
(point.sponsor == _sponsor) );
}
// getSponsoringCount(): returns the number of points _sponsor is
// providing service to
//
function getSponsoringCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return sponsoring[_sponsor].length;
}
// getSponsoring(): returns a list of points _sponsor is providing
// service to
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSponsoring(uint32 _sponsor)
view
external
returns (uint32[] sponsees)
{
return sponsoring[_sponsor];
}
// escaping
// isEscaping(): returns true if _point has an outstanding escape request
//
function isEscaping(uint32 _point)
view
external
returns (bool escaping)
{
return points[_point].escapeRequested;
}
// getEscapeRequest(): returns _point's current escape request
//
// the returned escape request is only valid as long as isEscaping()
// returns true
//
function getEscapeRequest(uint32 _point)
view
external
returns (uint32 escape)
{
return points[_point].escapeRequestedTo;
}
// isRequestingEscapeTo(): returns true if _point has an outstanding
// escape request targetting _sponsor
//
function isRequestingEscapeTo(uint32 _point, uint32 _sponsor)
view
public
returns (bool equals)
{
Point storage point = points[_point];
return (point.escapeRequested && (point.escapeRequestedTo == _sponsor));
}
// getEscapeRequestsCount(): returns the number of points _sponsor
// is providing service to
//
function getEscapeRequestsCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return escapeRequests[_sponsor].length;
}
// getEscapeRequests(): get the points _sponsor has received escape
// requests from
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getEscapeRequests(uint32 _sponsor)
view
external
returns (uint32[] requests)
{
return escapeRequests[_sponsor];
}
//
// Point writing
//
// activatePoint(): activate a point, register it as spawned by its prefix
//
function activatePoint(uint32 _point)
onlyOwner
external
{
// make a point active, setting its sponsor to its prefix
//
Point storage point = points[_point];
require(!point.active);
point.active = true;
registerSponsor(_point, true, getPrefix(_point));
emit Activated(_point);
}
// setKeys(): set network public keys of _point to _encryptionKey and
// _authenticationKey, with the specified _cryptoSuiteVersion
//
function setKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion)
onlyOwner
external
{
Point storage point = points[_point];
if ( point.encryptionKey == _encryptionKey &&
point.authenticationKey == _authenticationKey &&
point.cryptoSuiteVersion == _cryptoSuiteVersion )
{
return;
}
point.encryptionKey = _encryptionKey;
point.authenticationKey = _authenticationKey;
point.cryptoSuiteVersion = _cryptoSuiteVersion;
point.keyRevisionNumber++;
emit ChangedKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion,
point.keyRevisionNumber);
}
// incrementContinuityNumber(): break continuity for _point
//
function incrementContinuityNumber(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
point.continuityNumber++;
emit BrokeContinuity(_point, point.continuityNumber);
}
// registerSpawn(): add a point to its prefix's list of spawned points
//
function registerSpawned(uint32 _point)
onlyOwner
external
{
// if a point is its own prefix (a galaxy) then don't register it
//
uint32 prefix = getPrefix(_point);
if (prefix == _point)
{
return;
}
// register a new spawned point for the prefix
//
points[prefix].spawned.push(_point);
emit Spawned(prefix, _point);
}
// loseSponsor(): indicates that _point's sponsor is no longer providing
// it service
//
function loseSponsor(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.hasSponsor)
{
return;
}
registerSponsor(_point, false, point.sponsor);
emit LostSponsor(_point, point.sponsor);
}
// setEscapeRequest(): for _point, start an escape request to _sponsor
//
function setEscapeRequest(uint32 _point, uint32 _sponsor)
onlyOwner
external
{
if (isRequestingEscapeTo(_point, _sponsor))
{
return;
}
registerEscapeRequest(_point, true, _sponsor);
emit EscapeRequested(_point, _sponsor);
}
// cancelEscape(): for _point, stop the current escape request, if any
//
function cancelEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.escapeRequested)
{
return;
}
uint32 request = point.escapeRequestedTo;
registerEscapeRequest(_point, false, 0);
emit EscapeCanceled(_point, request);
}
// doEscape(): perform the requested escape
//
function doEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
require(point.escapeRequested);
registerSponsor(_point, true, point.escapeRequestedTo);
registerEscapeRequest(_point, false, 0);
emit EscapeAccepted(_point, point.sponsor);
}
//
// Point utils
//
// getPrefix(): compute prefix ("parent") of _point
//
function getPrefix(uint32 _point)
pure
public
returns (uint16 prefix)
{
if (_point < 0x10000)
{
return uint16(_point % 0x100);
}
return uint16(_point % 0x10000);
}
// getPointSize(): return the size of _point
//
function getPointSize(uint32 _point)
external
pure
returns (Size _size)
{
if (_point < 0x100) return Size.Galaxy;
if (_point < 0x10000) return Size.Star;
return Size.Planet;
}
// internal use
// registerSponsor(): set the sponsorship state of _point and update the
// reverse lookup for sponsors
//
function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor)
internal
{
Point storage point = points[_point];
bool had = point.hasSponsor;
uint32 prev = point.sponsor;
// if we didn't have a sponsor, and won't get one,
// or if we get the sponsor we already have,
// nothing will change, so jump out early.
//
if ( (!had && !_hasSponsor) ||
(had && _hasSponsor && prev == _sponsor) )
{
return;
}
// if the point used to have a different sponsor, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (had)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = sponsoringIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :sponsoringIndexes reference
//
uint32[] storage prevSponsoring = sponsoring[prev];
uint256 last = prevSponsoring.length - 1;
uint32 moved = prevSponsoring[last];
prevSponsoring[i] = moved;
sponsoringIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSponsoring[last]);
prevSponsoring.length = last;
sponsoringIndexes[prev][_point] = 0;
}
if (_hasSponsor)
{
uint32[] storage newSponsoring = sponsoring[_sponsor];
newSponsoring.push(_point);
sponsoringIndexes[_sponsor][_point] = newSponsoring.length;
}
point.sponsor = _sponsor;
point.hasSponsor = _hasSponsor;
}
// registerEscapeRequest(): set the escape state of _point and update the
// reverse lookup for sponsors
//
function registerEscapeRequest( uint32 _point,
bool _isEscaping, uint32 _sponsor )
internal
{
Point storage point = points[_point];
bool was = point.escapeRequested;
uint32 prev = point.escapeRequestedTo;
// if we weren't escaping, and won't be,
// or if we were escaping, and the new target is the same,
// nothing will change, so jump out early.
//
if ( (!was && !_isEscaping) ||
(was && _isEscaping && prev == _sponsor) )
{
return;
}
// if the point used to have a different request, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (was)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = escapeRequestsIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :escapeRequestsIndexes reference
//
uint32[] storage prevRequests = escapeRequests[prev];
uint256 last = prevRequests.length - 1;
uint32 moved = prevRequests[last];
prevRequests[i] = moved;
escapeRequestsIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevRequests[last]);
prevRequests.length = last;
escapeRequestsIndexes[prev][_point] = 0;
}
if (_isEscaping)
{
uint32[] storage newRequests = escapeRequests[_sponsor];
newRequests.push(_point);
escapeRequestsIndexes[_sponsor][_point] = newRequests.length;
}
point.escapeRequestedTo = _sponsor;
point.escapeRequested = _isEscaping;
}
//
// Deed reading
//
// owner
// getOwner(): return owner of _point
//
function getOwner(uint32 _point)
view
external
returns (address owner)
{
return rights[_point].owner;
}
// isOwner(): true if _point is owned by _address
//
function isOwner(uint32 _point, address _address)
view
external
returns (bool result)
{
return (rights[_point].owner == _address);
}
// getOwnedPointCount(): return length of array of points that _whose owns
//
function getOwnedPointCount(address _whose)
view
external
returns (uint256 count)
{
return pointsOwnedBy[_whose].length;
}
// getOwnedPoints(): return array of points that _whose owns
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getOwnedPoints(address _whose)
view
external
returns (uint32[] ownedPoints)
{
return pointsOwnedBy[_whose];
}
// getOwnedPointAtIndex(): get point at _index from array of points that
// _whose owns
//
function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
{
uint32[] storage owned = pointsOwnedBy[_whose];
require(_index < owned.length);
return owned[_index];
}
// management proxy
// getManagementProxy(): returns _point's current management proxy
//
function getManagementProxy(uint32 _point)
view
external
returns (address manager)
{
return rights[_point].managementProxy;
}
// isManagementProxy(): returns true if _proxy is _point's management proxy
//
function isManagementProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].managementProxy == _proxy);
}
// canManage(): true if _who is the owner or manager of _point
//
function canManage(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.managementProxy) ) );
}
// getManagerForCount(): returns the amount of points _proxy can manage
//
function getManagerForCount(address _proxy)
view
external
returns (uint256 count)
{
return managerFor[_proxy].length;
}
// getManagerFor(): returns the points _proxy can manage
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getManagerFor(address _proxy)
view
external
returns (uint32[] mfor)
{
return managerFor[_proxy];
}
// spawn proxy
// getSpawnProxy(): returns _point's current spawn proxy
//
function getSpawnProxy(uint32 _point)
view
external
returns (address spawnProxy)
{
return rights[_point].spawnProxy;
}
// isSpawnProxy(): returns true if _proxy is _point's spawn proxy
//
function isSpawnProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].spawnProxy == _proxy);
}
// canSpawnAs(): true if _who is the owner or spawn proxy of _point
//
function canSpawnAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.spawnProxy) ) );
}
// getSpawningForCount(): returns the amount of points _proxy
// can spawn with
//
function getSpawningForCount(address _proxy)
view
external
returns (uint256 count)
{
return spawningFor[_proxy].length;
}
// getSpawningFor(): get the points _proxy can spawn with
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawningFor(address _proxy)
view
external
returns (uint32[] sfor)
{
return spawningFor[_proxy];
}
// voting proxy
// getVotingProxy(): returns _point's current voting proxy
//
function getVotingProxy(uint32 _point)
view
external
returns (address voter)
{
return rights[_point].votingProxy;
}
// isVotingProxy(): returns true if _proxy is _point's voting proxy
//
function isVotingProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].votingProxy == _proxy);
}
// canVoteAs(): true if _who is the owner of _point,
// or the voting proxy of _point's owner
//
function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.votingProxy) ) );
}
// getVotingForCount(): returns the amount of points _proxy can vote as
//
function getVotingForCount(address _proxy)
view
external
returns (uint256 count)
{
return votingFor[_proxy].length;
}
// getVotingFor(): returns the points _proxy can vote as
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
{
return votingFor[_proxy];
}
// transfer proxy
// getTransferProxy(): returns _point's current transfer proxy
//
function getTransferProxy(uint32 _point)
view
external
returns (address transferProxy)
{
return rights[_point].transferProxy;
}
// isTransferProxy(): returns true if _proxy is _point's transfer proxy
//
function isTransferProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].transferProxy == _proxy);
}
// canTransfer(): true if _who is the owner or transfer proxy of _point,
// or is an operator for _point's current owner
//
function canTransfer(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.transferProxy) ||
operators[deed.owner][_who] ) );
}
// getTransferringForCount(): returns the amount of points _proxy
// can transfer
//
function getTransferringForCount(address _proxy)
view
external
returns (uint256 count)
{
return transferringFor[_proxy].length;
}
// getTransferringFor(): get the points _proxy can transfer
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getTransferringFor(address _proxy)
view
external
returns (uint32[] tfor)
{
return transferringFor[_proxy];
}
// isOperator(): returns true if _operator is allowed to transfer
// ownership of _owner's points
//
function isOperator(address _owner, address _operator)
view
external
returns (bool result)
{
return operators[_owner][_operator];
}
//
// Deed writing
//
// setOwner(): set owner of _point to _owner
//
// Note: setOwner() only implements the minimal data storage
// logic for a transfer; the full transfer is implemented in
// Ecliptic.
//
// Note: _owner must not be the zero address.
//
function setOwner(uint32 _point, address _owner)
onlyOwner
external
{
// prevent burning of points by making zero the owner
//
require(0x0 != _owner);
// prev: previous owner, if any
//
address prev = rights[_point].owner;
if (prev == _owner)
{
return;
}
// if the point used to have a different owner, do some gymnastics to
// keep the list of owned points gapless. delete this point from the
// list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous owner's list of owned points
//
uint256 i = pointOwnerIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :pointOwnerIndexes reference
//
uint32[] storage owner = pointsOwnedBy[prev];
uint256 last = owner.length - 1;
uint32 moved = owner[last];
owner[i] = moved;
pointOwnerIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(owner[last]);
owner.length = last;
pointOwnerIndexes[prev][_point] = 0;
}
// update the owner list and the owner's index list
//
rights[_point].owner = _owner;
pointsOwnedBy[_owner].push(_point);
pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length;
emit OwnerChanged(_point, _owner);
}
// setManagementProxy(): makes _proxy _point's management proxy
//
function setManagementProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.managementProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different manager, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old manager's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous manager's list of managed points
//
uint256 i = managerForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :managerForIndexes reference
//
uint32[] storage prevMfor = managerFor[prev];
uint256 last = prevMfor.length - 1;
uint32 moved = prevMfor[last];
prevMfor[i] = moved;
managerForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevMfor[last]);
prevMfor.length = last;
managerForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage mfor = managerFor[_proxy];
mfor.push(_point);
managerForIndexes[_proxy][_point] = mfor.length;
}
deed.managementProxy = _proxy;
emit ChangedManagementProxy(_point, _proxy);
}
// setSpawnProxy(): makes _proxy _point's spawn proxy
//
function setSpawnProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.spawnProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different spawn proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of spawning points
//
uint256 i = spawningForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :spawningForIndexes reference
//
uint32[] storage prevSfor = spawningFor[prev];
uint256 last = prevSfor.length - 1;
uint32 moved = prevSfor[last];
prevSfor[i] = moved;
spawningForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSfor[last]);
prevSfor.length = last;
spawningForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage sfor = spawningFor[_proxy];
sfor.push(_point);
spawningForIndexes[_proxy][_point] = sfor.length;
}
deed.spawnProxy = _proxy;
emit ChangedSpawnProxy(_point, _proxy);
}
// setVotingProxy(): makes _proxy _point's voting proxy
//
function setVotingProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.votingProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different voter, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old voter's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous voter's list of points it was
// voting for
//
uint256 i = votingForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :votingForIndexes reference
//
uint32[] storage prevVfor = votingFor[prev];
uint256 last = prevVfor.length - 1;
uint32 moved = prevVfor[last];
prevVfor[i] = moved;
votingForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevVfor[last]);
prevVfor.length = last;
votingForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage vfor = votingFor[_proxy];
vfor.push(_point);
votingForIndexes[_proxy][_point] = vfor.length;
}
deed.votingProxy = _proxy;
emit ChangedVotingProxy(_point, _proxy);
}
// setManagementProxy(): makes _proxy _point's transfer proxy
//
function setTransferProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.transferProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different transfer proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of transferable points
//
uint256 i = transferringForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :transferringForIndexes reference
//
uint32[] storage prevTfor = transferringFor[prev];
uint256 last = prevTfor.length - 1;
uint32 moved = prevTfor[last];
prevTfor[i] = moved;
transferringForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevTfor[last]);
prevTfor.length = last;
transferringForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage tfor = transferringFor[_proxy];
tfor.push(_point);
transferringForIndexes[_proxy][_point] = tfor.length;
}
deed.transferProxy = _proxy;
emit ChangedTransferProxy(_point, _proxy);
}
// setOperator(): dis/allow _operator to transfer ownership of all points
// owned by _owner
//
// operators are part of the ERC721 standard
//
function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
{
operators[_owner][_operator] = _approved;
}
}
// Azimuth's ReadsAzimuth.sol
// ReadsAzimuth: referring to and testing against the Azimuth
// data contract
//
// To avoid needless repetition, this contract provides common
// checks and operations using the Azimuth contract.
//
contract ReadsAzimuth
{
// azimuth: points data storage contract.
//
Azimuth public azimuth;
// constructor(): set the Azimuth data contract's address
//
constructor(Azimuth _azimuth)
public
{
azimuth = _azimuth;
}
// activePointOwner(): require that :msg.sender is the owner of _point,
// and that _point is active
//
modifier activePointOwner(uint32 _point)
{
require( azimuth.isOwner(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointManager(): require that :msg.sender can manage _point,
// and that _point is active
//
modifier activePointManager(uint32 _point)
{
require( azimuth.canManage(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointSpawner(): require that :msg.sender can spawn as _point,
// and that _point is active
//
modifier activePointSpawner(uint32 _point)
{
require( azimuth.canSpawnAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointVoter(): require that :msg.sender can vote as _point,
// and that _point is active
//
modifier activePointVoter(uint32 _point)
{
require( azimuth.canVoteAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
// Azimuth's Polls.sol
// Polls: proposals & votes data contract
//
// This contract is used for storing all data related to the proposals
// of the senate (galaxy owners) and their votes on those proposals.
// It keeps track of votes and uses them to calculate whether a majority
// is in favor of a proposal.
//
// Every galaxy can only vote on a proposal exactly once. Votes cannot
// be changed. If a proposal fails to achieve majority within its
// duration, it can be restarted after its cooldown period has passed.
//
// The requirements for a proposal to achieve majority are as follows:
// - At least 1/4 of the currently active voters (rounded down) must have
// voted in favor of the proposal,
// - More than half of the votes cast must be in favor of the proposal,
// and this can no longer change, either because
// - the poll duration has passed, or
// - not enough voters remain to take away the in-favor majority.
// As soon as these conditions are met, no further interaction with
// the proposal is possible. Achieving majority is permanent.
//
// Since data stores are difficult to upgrade, all of the logic unrelated
// to the voting itself (that is, determining who is eligible to vote)
// is expected to be implemented by this contract's owner.
//
// This contract will be owned by the Ecliptic contract.
//
contract Polls is Ownable
{
using SafeMath for uint256;
using SafeMath16 for uint16;
using SafeMath8 for uint8;
// UpgradePollStarted: a poll on :proposal has opened
//
event UpgradePollStarted(address proposal);
// DocumentPollStarted: a poll on :proposal has opened
//
event DocumentPollStarted(bytes32 proposal);
// UpgradeMajority: :proposal has achieved majority
//
event UpgradeMajority(address proposal);
// DocumentMajority: :proposal has achieved majority
//
event DocumentMajority(bytes32 proposal);
// Poll: full poll state
//
struct Poll
{
// start: the timestamp at which the poll was started
//
uint256 start;
// voted: per galaxy, whether they have voted on this poll
//
bool[256] voted;
// yesVotes: amount of votes in favor of the proposal
//
uint16 yesVotes;
// noVotes: amount of votes against the proposal
//
uint16 noVotes;
// duration: amount of time during which the poll can be voted on
//
uint256 duration;
// cooldown: amount of time before the (non-majority) poll can be reopened
//
uint256 cooldown;
}
// pollDuration: duration set for new polls. see also Poll.duration above
//
uint256 public pollDuration;
// pollCooldown: cooldown set for new polls. see also Poll.cooldown above
//
uint256 public pollCooldown;
// totalVoters: amount of active galaxies
//
uint16 public totalVoters;
// upgradeProposals: list of all upgrades ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
address[] public upgradeProposals;
// upgradePolls: per address, poll held to determine if that address
// will become the new ecliptic
//
mapping(address => Poll) public upgradePolls;
// upgradeHasAchievedMajority: per address, whether that address
// has ever achieved majority
//
// If we did not store this, we would have to look at old poll data
// to see whether or not a proposal has ever achieved majority.
// Since the outcome of a poll is calculated based on :totalVoters,
// which may not be consistent across time, we need to store outcomes
// explicitly instead of re-calculating them. This allows us to always
// tell with certainty whether or not a majority was achieved,
// regardless of the current :totalVoters.
//
mapping(address => bool) public upgradeHasAchievedMajority;
// documentProposals: list of all documents ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
bytes32[] public documentProposals;
// documentPolls: per hash, poll held to determine if the corresponding
// document is accepted by the galactic senate
//
mapping(bytes32 => Poll) public documentPolls;
// documentHasAchievedMajority: per hash, whether that hash has ever
// achieved majority
//
// the note for upgradeHasAchievedMajority above applies here as well
//
mapping(bytes32 => bool) public documentHasAchievedMajority;
// documentMajorities: all hashes that have achieved majority
//
bytes32[] public documentMajorities;
// constructor(): initial contract configuration
//
constructor(uint256 _pollDuration, uint256 _pollCooldown)
public
{
reconfigure(_pollDuration, _pollCooldown);
}
// reconfigure(): change poll duration and cooldown
//
function reconfigure(uint256 _pollDuration, uint256 _pollCooldown)
public
onlyOwner
{
require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) &&
(5 days <= _pollCooldown) && (_pollCooldown <= 90 days) );
pollDuration = _pollDuration;
pollCooldown = _pollCooldown;
}
// incrementTotalVoters(): increase the amount of registered voters
//
function incrementTotalVoters()
external
onlyOwner
{
require(totalVoters < 256);
totalVoters = totalVoters.add(1);
}
// getAllUpgradeProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getUpgradeProposals()
external
view
returns (address[] proposals)
{
return upgradeProposals;
}
// getUpgradeProposalCount(): get the number of unique proposed upgrades
//
function getUpgradeProposalCount()
external
view
returns (uint256 count)
{
return upgradeProposals.length;
}
// getAllDocumentProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentProposals()
external
view
returns (bytes32[] proposals)
{
return documentProposals;
}
// getDocumentProposalCount(): get the number of unique proposed upgrades
//
function getDocumentProposalCount()
external
view
returns (uint256 count)
{
return documentProposals.length;
}
// getDocumentMajorities(): return array of all document majorities
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentMajorities()
external
view
returns (bytes32[] majorities)
{
return documentMajorities;
}
// hasVotedOnUpgradePoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal)
external
view
returns (bool result)
{
return upgradePolls[_proposal].voted[_galaxy];
}
// hasVotedOnDocumentPoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
view
returns (bool result)
{
return documentPolls[_proposal].voted[_galaxy];
}
// startUpgradePoll(): open a poll on making _proposal the new ecliptic
//
function startUpgradePoll(address _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
Poll storage poll = upgradePolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
upgradeProposals.push(_proposal);
}
startPoll(poll);
emit UpgradePollStarted(_proposal);
}
// startDocumentPoll(): open a poll on accepting the document
// whose hash is _proposal
//
function startDocumentPoll(bytes32 _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
Poll storage poll = documentPolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
documentProposals.push(_proposal);
}
startPoll(poll);
emit DocumentPollStarted(_proposal);
}
// startPoll(): open a new poll, or re-open an old one
//
function startPoll(Poll storage _poll)
internal
{
// check that the poll has cooled down enough to be started again
//
// for completely new polls, the values used will be zero
//
require( block.timestamp > ( _poll.start.add(
_poll.duration.add(
_poll.cooldown )) ) );
// set started poll state
//
_poll.start = block.timestamp;
delete _poll.voted;
_poll.yesVotes = 0;
_poll.noVotes = 0;
_poll.duration = pollDuration;
_poll.cooldown = pollCooldown;
}
// castUpgradeVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castUpgradeVote(uint8 _as, address _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = upgradePolls[_proposal];
processVote(poll, _as, _vote);
return updateUpgradePoll(_proposal);
}
// castDocumentVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = documentPolls[_proposal];
processVote(poll, _as, _vote);
return updateDocumentPoll(_proposal);
}
// processVote(): record a vote from _as on the _poll
//
function processVote(Poll storage _poll, uint8 _as, bool _vote)
internal
{
// assist symbolic execution tools
//
assert(block.timestamp >= _poll.start);
require( // may only vote once
//
!_poll.voted[_as] &&
//
// may only vote when the poll is open
//
(block.timestamp < _poll.start.add(_poll.duration)) );
// update poll state to account for the new vote
//
_poll.voted[_as] = true;
if (_vote)
{
_poll.yesVotes = _poll.yesVotes.add(1);
}
else
{
_poll.noVotes = _poll.noVotes.add(1);
}
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, updating state, sending an event,
// and returning true if it has
//
function updateUpgradePoll(address _proposal)
public
onlyOwner
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = upgradePolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update the state and send an event
//
if (majority)
{
upgradeHasAchievedMajority[_proposal] = true;
emit UpgradeMajority(_proposal);
}
return majority;
}
// updateDocumentPoll(): check whether the _proposal has achieved majority,
// updating the state and sending an event if it has
//
// this can be called by anyone, because the ecliptic does not
// need to be aware of the result
//
function updateDocumentPoll(bytes32 _proposal)
public
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = documentPolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update state and send an event
//
if (majority)
{
documentHasAchievedMajority[_proposal] = true;
documentMajorities.push(_proposal);
emit DocumentMajority(_proposal);
}
return majority;
}
// checkPollMajority(): returns true if the majority is in favor of
// the subject of the poll
//
function checkPollMajority(Poll _poll)
internal
view
returns (bool majority)
{
return ( // poll must have at least the minimum required yes-votes
//
(_poll.yesVotes >= (totalVoters / 4)) &&
//
// and have a majority...
//
(_poll.yesVotes > _poll.noVotes) &&
//
// ...that is indisputable
//
( // either because the poll has ended
//
(block.timestamp > _poll.start.add(_poll.duration)) ||
//
// or there are more yes votes than there can be no votes
//
( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) );
}
}
// Azimuth's Claims.sol
// Claims: simple identity management
//
// This contract allows points to document claims about their owner.
// Most commonly, these are about identity, with a claim's protocol
// defining the context or platform of the claim, and its dossier
// containing proof of its validity.
// Points are limited to a maximum of 16 claims.
//
// For existing claims, the dossier can be updated, or the claim can
// be removed entirely. It is recommended to remove any claims associated
// with a point when it is about to be transferred to a new owner.
// For convenience, the owner of the Azimuth contract (the Ecliptic)
// is allowed to clear claims for any point, allowing it to do this for
// you on-transfer.
//
contract Claims is ReadsAzimuth
{
// ClaimAdded: a claim was added by :by
//
event ClaimAdded( uint32 indexed by,
string _protocol,
string _claim,
bytes _dossier );
// ClaimRemoved: a claim was removed by :by
//
event ClaimRemoved(uint32 indexed by, string _protocol, string _claim);
// maxClaims: the amount of claims that can be registered per point
//
uint8 constant maxClaims = 16;
// Claim: claim details
//
struct Claim
{
// protocol: context of the claim
//
string protocol;
// claim: the claim itself
//
string claim;
// dossier: data relating to the claim, as proof
//
bytes dossier;
}
// per point, list of claims
//
mapping(uint32 => Claim[maxClaims]) public claims;
// constructor(): register the azimuth contract.
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// addClaim(): register a claim as _point
//
function addClaim(uint32 _point,
string _protocol,
string _claim,
bytes _dossier)
external
activePointManager(_point)
{
// require non-empty protocol and claim fields
//
require( ( 0 < bytes(_protocol).length ) &&
( 0 < bytes(_claim).length ) );
// cur: index + 1 of the claim if it already exists, 0 otherwise
//
uint8 cur = findClaim(_point, _protocol, _claim);
// if the claim doesn't yet exist, store it in state
//
if (cur == 0)
{
// if there are no empty slots left, this throws
//
uint8 empty = findEmptySlot(_point);
claims[_point][empty] = Claim(_protocol, _claim, _dossier);
}
//
// if the claim has been made before, update the version in state
//
else
{
claims[_point][cur-1] = Claim(_protocol, _claim, _dossier);
}
emit ClaimAdded(_point, _protocol, _claim, _dossier);
}
// removeClaim(): unregister a claim as _point
//
function removeClaim(uint32 _point, string _protocol, string _claim)
external
activePointManager(_point)
{
// i: current index + 1 in _point's list of claims
//
uint256 i = findClaim(_point, _protocol, _claim);
// we store index + 1, because 0 is the eth default value
// can only delete an existing claim
//
require(i > 0);
i--;
// clear out the claim
//
delete claims[_point][i];
emit ClaimRemoved(_point, _protocol, _claim);
}
// clearClaims(): unregister all of _point's claims
//
// can also be called by the ecliptic during point transfer
//
function clearClaims(uint32 _point)
external
{
// both point owner and ecliptic may do this
//
// We do not necessarily need to check for _point's active flag here,
// since inactive points cannot have claims set. Doing the check
// anyway would make this function slightly harder to think about due
// to its relation to Ecliptic's transferPoint().
//
require( azimuth.canManage(_point, msg.sender) ||
( msg.sender == azimuth.owner() ) );
Claim[maxClaims] storage currClaims = claims[_point];
// clear out all claims
//
for (uint8 i = 0; i < maxClaims; i++)
{
// only emit the removed event if there was a claim here
//
if ( 0 < bytes(currClaims[i].claim).length )
{
emit ClaimRemoved(_point, currClaims[i].protocol, currClaims[i].claim);
}
delete currClaims[i];
}
}
// findClaim(): find the index of the specified claim
//
// returns 0 if not found, index + 1 otherwise
//
function findClaim(uint32 _whose, string _protocol, string _claim)
public
view
returns (uint8 index)
{
// we use hashes of the string because solidity can't do string
// comparison yet
//
bytes32 protocolHash = keccak256(bytes(_protocol));
bytes32 claimHash = keccak256(bytes(_claim));
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) &&
( claimHash == keccak256(bytes(thisClaim.claim)) ) )
{
return i+1;
}
}
return 0;
}
// findEmptySlot(): find the index of the first empty claim slot
//
// returns the index of the slot, throws if there are no empty slots
//
function findEmptySlot(uint32 _whose)
internal
view
returns (uint8 index)
{
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( (0 == bytes(thisClaim.claim).length) )
{
return i;
}
}
revert();
}
}
// Treasury's ITreasuryProxy
interface ITreasuryProxy {
function upgradeTo(address _impl) external returns (bool);
function freeze() external returns (bool);
}
// Azimuth's EclipticBase.sol
// EclipticBase: upgradable ecliptic
//
// This contract implements the upgrade logic for the Ecliptic.
// Newer versions of the Ecliptic are expected to provide at least
// the onUpgrade() function. If they don't, upgrading to them will
// fail.
//
// Note that even though this contract doesn't specify any required
// interface members aside from upgrade() and onUpgrade(), contracts
// and clients may still rely on the presence of certain functions
// provided by the Ecliptic proper. Keep this in mind when writing
// new versions of it.
//
contract EclipticBase is Ownable, ReadsAzimuth
{
// Upgraded: _to is the new canonical Ecliptic
//
event Upgraded(address to);
// polls: senate voting contract
//
Polls public polls;
// previousEcliptic: address of the previous ecliptic this
// instance expects to upgrade from, stored and
// checked for to prevent unexpected upgrade paths
//
address public previousEcliptic;
constructor( address _previous,
Azimuth _azimuth,
Polls _polls )
ReadsAzimuth(_azimuth)
internal
{
previousEcliptic = _previous;
polls = _polls;
}
// onUpgrade(): called by previous ecliptic when upgrading
//
// in future ecliptics, this might perform more logic than
// just simple checks and verifications.
// when overriding this, make sure to call this original as well.
//
function onUpgrade()
external
{
// make sure this is the expected upgrade path,
// and that we have gotten the ownership we require
//
require( msg.sender == previousEcliptic &&
this == azimuth.owner() &&
this == polls.owner() );
}
// upgrade(): transfer ownership of the ecliptic data to the new
// ecliptic contract, notify it, then self-destruct.
//
// Note: any eth that have somehow ended up in this contract
// are also sent to the new ecliptic.
//
function upgrade(EclipticBase _new)
internal
{
// transfer ownership of the data contracts
//
azimuth.transferOwnership(_new);
polls.transferOwnership(_new);
// trigger upgrade logic on the target contract
//
_new.onUpgrade();
// emit event and destroy this contract
//
emit Upgraded(_new);
selfdestruct(_new);
}
}
////////////////////////////////////////////////////////////////////////////////
// Ecliptic
////////////////////////////////////////////////////////////////////////////////
// Ecliptic: logic for interacting with the Azimuth ledger
//
// This contract is the point of entry for all operations on the Azimuth
// ledger as stored in the Azimuth data contract. The functions herein
// are responsible for performing all necessary business logic.
// Examples of such logic include verifying permissions of the caller
// and ensuring a requested change is actually valid.
// Point owners can always operate on their own points. Ethereum addresses
// can also perform specific operations if they've been given the
// appropriate permissions. (For example, managers for general management,
// spawn proxies for spawning child points, etc.)
//
// This contract uses external contracts (Azimuth, Polls) for data storage
// so that it itself can easily be replaced in case its logic needs to
// be changed. In other words, it can be upgraded. It does this by passing
// ownership of the data contracts to a new Ecliptic contract.
//
// Because of this, it is advised for clients to not store this contract's
// address directly, but rather ask the Azimuth contract for its owner
// attribute to ensure transactions get sent to the latest Ecliptic.
// Alternatively, the ENS name ecliptic.eth will resolve to the latest
// Ecliptic as well.
//
// Upgrading happens based on polls held by the senate (galaxy owners).
// Through this contract, the senate can submit proposals, opening polls
// for the senate to cast votes on. These proposals can be either hashes
// of documents or addresses of new Ecliptics.
// If an ecliptic proposal gains majority, this contract will transfer
// ownership of the data storage contracts to that address, so that it may
// operate on the data they contain. This contract will selfdestruct at
// the end of the upgrade process.
//
// This contract implements the ERC721 interface for non-fungible tokens,
// allowing points to be managed using generic clients that support the
// standard. It also implements ERC165 to allow this to be discovered.
//
contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata
{
using SafeMath for uint256;
using AddressUtils for address;
// Transfer: This emits when ownership of any NFT changes by any mechanism.
// This event emits when NFTs are created (`from` == 0) and
// destroyed (`to` == 0). At the time of any transfer, the
// approved address for that NFT (if any) is reset to none.
//
event Transfer(address indexed _from, address indexed _to,
uint256 indexed _tokenId);
// Approval: This emits when the approved address for an NFT is changed or
// reaffirmed. The zero address indicates there is no approved
// address. When a Transfer event emits, this also indicates that
// the approved address for that NFT (if any) is reset to none.
//
event Approval(address indexed _owner, address indexed _approved,
uint256 indexed _tokenId);
// ApprovalForAll: This emits when an operator is enabled or disabled for an
// owner. The operator can manage all NFTs of the owner.
//
event ApprovalForAll(address indexed _owner, address indexed _operator,
bool _approved);
// erc721Received: equal to:
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
// which can be also obtained as:
// ERC721Receiver(0).onERC721Received.selector`
bytes4 constant erc721Received = 0x150b7a02;
// depositAddress: Special address respresenting L2. Ships sent to
// this address are controlled on L2 instead of here.
//
address constant public depositAddress =
0x1111111111111111111111111111111111111111;
ITreasuryProxy public treasuryProxy;
// treasuryUpgradeHash
// hash of the treasury implementation to upgrade to
// Note: stand-in, just hash of no bytes
// could be made immutable and passed in as constructor argument
bytes32 constant public treasuryUpgradeHash = hex"26f3eae628fa1a4d23e34b91a4d412526a47620ced37c80928906f9fa07c0774";
bool public treasuryUpgraded = false;
// claims: contract reference, for clearing claims on-transfer
//
Claims public claims;
// constructor(): set data contract addresses and signal interface support
//
// Note: during first deploy, ownership of these data contracts must
// be manually transferred to this contract.
//
constructor(address _previous,
Azimuth _azimuth,
Polls _polls,
Claims _claims,
ITreasuryProxy _treasuryProxy)
EclipticBase(_previous, _azimuth, _polls)
public
{
claims = _claims;
treasuryProxy = _treasuryProxy;
// register supported interfaces for ERC165
//
_registerInterface(0x80ac58cd); // ERC721
_registerInterface(0x5b5e139f); // ERC721Metadata
_registerInterface(0x7f5828d0); // ERC173 (ownership)
}
//
// ERC721 interface
//
// balanceOf(): get the amount of points owned by _owner
//
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
require(0x0 != _owner);
return azimuth.getOwnedPointCount(_owner);
}
// ownerOf(): get the current owner of point _tokenId
//
function ownerOf(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address owner)
{
uint32 id = uint32(_tokenId);
// this will throw if the owner is the zero address,
// active points always have a valid owner.
//
require(azimuth.isActive(id));
return azimuth.getOwner(id);
}
// exists(): returns true if point _tokenId is active
//
function exists(uint256 _tokenId)
public
view
returns (bool doesExist)
{
return ( (_tokenId < 0x100000000) &&
azimuth.isActive(uint32(_tokenId)) );
}
// safeTransferFrom(): transfer point _tokenId from _from to _to
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public
{
// transfer with empty data
//
safeTransferFrom(_from, _to, _tokenId, "");
}
// safeTransferFrom(): transfer point _tokenId from _from to _to,
// and call recipient if it's a contract
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId,
bytes _data)
public
{
// perform raw transfer
//
transferFrom(_from, _to, _tokenId);
// do the callback last to avoid re-entrancy
//
if (_to.isContract())
{
bytes4 retval = ERC721Receiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data);
//
// standard return idiom to confirm contract semantics
//
require(retval == erc721Received);
}
}
// transferFrom(): transfer point _tokenId from _from to _to,
// WITHOUT notifying recipient contract
//
function transferFrom(address _from, address _to, uint256 _tokenId)
public
validPointId(_tokenId)
{
uint32 id = uint32(_tokenId);
require(azimuth.isOwner(id, _from));
// the ERC721 operator/approved address (if any) is
// accounted for in transferPoint()
//
transferPoint(id, _to, true);
}
// approve(): allow _approved to transfer ownership of point
// _tokenId
//
function approve(address _approved, uint256 _tokenId)
public
validPointId(_tokenId)
{
setTransferProxy(uint32(_tokenId), _approved);
}
// setApprovalForAll(): allow or disallow _operator to
// transfer ownership of ALL points
// owned by :msg.sender
//
function setApprovalForAll(address _operator, bool _approved)
public
{
require(0x0 != _operator);
azimuth.setOperator(msg.sender, _operator, _approved);
emit ApprovalForAll(msg.sender, _operator, _approved);
}
// getApproved(): get the approved address for point _tokenId
//
function getApproved(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address approved)
{
//NOTE redundant, transfer proxy cannot be set for
// inactive points
//
require(azimuth.isActive(uint32(_tokenId)));
return azimuth.getTransferProxy(uint32(_tokenId));
}
// isApprovedForAll(): returns true if _operator is an
// operator for _owner
//
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool result)
{
return azimuth.isOperator(_owner, _operator);
}
//
// ERC721Metadata interface
//
// name(): returns the name of a collection of points
//
function name()
external
view
returns (string)
{
return "Azimuth Points";
}
// symbol(): returns an abbreviates name for points
//
function symbol()
external
view
returns (string)
{
return "AZP";
}
// tokenURI(): returns a URL to an ERC-721 standard JSON file
//
function tokenURI(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (string _tokenURI)
{
_tokenURI = "https://azimuth.network/erc721/0000000000.json";
bytes memory _tokenURIBytes = bytes(_tokenURI);
_tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10);
_tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10);
_tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10);
_tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10);
_tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10);
_tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10);
_tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10);
_tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10);
_tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10);
_tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10);
}
//
// Points interface
//
// configureKeys(): configure _point with network public keys
// _encryptionKey, _authenticationKey,
// and corresponding _cryptoSuiteVersion,
// incrementing the point's continuity number if needed
//
function configureKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion,
bool _discontinuous)
external
activePointManager(_point)
onL1(_point)
{
if (_discontinuous)
{
azimuth.incrementContinuityNumber(_point);
}
azimuth.setKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion);
}
// spawn(): spawn _point, then either give, or allow _target to take,
// ownership of _point
//
// if _target is the :msg.sender, _targets owns the _point right away.
// otherwise, _target becomes the transfer proxy of _point.
//
// Requirements:
// - _point must not be active
// - _point must not be a planet with a galaxy prefix
// - _point's prefix must be linked and under its spawn limit
// - :msg.sender must be either the owner of _point's prefix,
// or an authorized spawn proxy for it
//
function spawn(uint32 _point, address _target)
external
{
// only currently unowned (and thus also inactive) points can be spawned
//
require(azimuth.isOwner(_point, 0x0));
// prefix: half-width prefix of _point
//
uint16 prefix = azimuth.getPrefix(_point);
// can't spawn if we deposited ownership or spawn rights to L2
//
require( depositAddress != azimuth.getOwner(prefix) );
require( depositAddress != azimuth.getSpawnProxy(prefix) );
// only allow spawning of points of the size directly below the prefix
//
// this is possible because of how the address space works,
// but supporting it introduces complexity through broken assumptions.
//
// example:
// 0x0000.0000 - galaxy zero
// 0x0000.0100 - the first star of galaxy zero
// 0x0001.0100 - the first planet of the first star
// 0x0001.0000 - the first planet of galaxy zero
//
require( (uint8(azimuth.getPointSize(prefix)) + 1) ==
uint8(azimuth.getPointSize(_point)) );
// prefix point must be linked and able to spawn
//
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
// the owner of a prefix can always spawn its children;
// other addresses need explicit permission (the role
// of "spawnProxy" in the Azimuth contract)
//
require( azimuth.canSpawnAs(prefix, msg.sender) );
// if the caller is spawning the point to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern
// making the _point prefix's owner the _point owner in the mean time
//
else
{
doSpawn(_point, _target, false, azimuth.getOwner(prefix));
}
}
// doSpawn(): actual spawning logic, used in spawn(). creates _point,
// making the _target its owner if _direct, or making the
// _holder the owner and the _target the transfer proxy
// if not _direct.
//
function doSpawn( uint32 _point,
address _target,
bool _direct,
address _holder )
internal
{
// register the spawn for _point's prefix, incrementing spawn count
//
azimuth.registerSpawned(_point);
// if the spawn is _direct, assume _target knows what they're doing
// and resolve right away
//
if (_direct)
{
// make the point active and set its new owner
//
azimuth.activatePoint(_point);
azimuth.setOwner(_point, _target);
emit Transfer(0x0, _target, uint256(_point));
}
//
// when spawning indirectly, enforce a withdraw pattern by approving
// the _target for transfer of the _point instead.
// we make the _holder the owner of this _point in the mean time,
// so that it may cancel the transfer (un-approve) if _target flakes.
// we don't make _point active yet, because it still doesn't really
// belong to anyone.
//
else
{
// have _holder hold on to the _point while _target gets to transfer
// ownership of it
//
azimuth.setOwner(_point, _holder);
azimuth.setTransferProxy(_point, _target);
emit Transfer(0x0, _holder, uint256(_point));
emit Approval(_holder, _target, uint256(_point));
}
}
// transferPoint(): transfer _point to _target, clearing all permissions
// data and keys if _reset is true
//
// Note: the _reset flag is useful when transferring the point to
// a recipient who doesn't trust the previous owner.
//
// We know _point is not on L2, since otherwise its owner would be
// depositAddress (which has no operator) and its transfer proxy
// would be zero.
//
// Requirements:
// - :msg.sender must be either _point's current owner, authorized
// to transfer _point, or authorized to transfer the current
// owner's points (as in ERC721's operator)
// - _target must not be the zero address
//
function transferPoint(uint32 _point, address _target, bool _reset)
public
{
// transfer is legitimate if the caller is the current owner, or
// an operator for the current owner, or the _point's transfer proxy
//
require(azimuth.canTransfer(_point, msg.sender));
// can't deposit galaxy to L2
// can't deposit contract-owned point to L2
//
require( depositAddress != _target ||
( azimuth.getPointSize(_point) != Azimuth.Size.Galaxy &&
!azimuth.getOwner(_point).isContract() ) );
// if the point wasn't active yet, that means transferring it
// is part of the "spawn" flow, so we need to activate it
//
if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
// if the owner would actually change, change it
//
// the only time this deliberately wouldn't be the case is when a
// prefix owner wants to activate a spawned but untransferred child.
//
if ( !azimuth.isOwner(_point, _target) )
{
// remember the previous owner, to be included in the Transfer event
//
address old = azimuth.getOwner(_point);
azimuth.setOwner(_point, _target);
// according to ERC721, the approved address (here, transfer proxy)
// gets cleared during every Transfer event
//
// we also rely on this so that transfer-related functions don't need
// to verify the point is on L1
//
azimuth.setTransferProxy(_point, 0);
emit Transfer(old, _target, uint256(_point));
}
// if we're depositing to L2, clear L1 data so that no proxies
// can be used
//
if ( depositAddress == _target )
{
azimuth.setKeys(_point, 0, 0, 0);
azimuth.setManagementProxy(_point, 0);
azimuth.setVotingProxy(_point, 0);
azimuth.setTransferProxy(_point, 0);
azimuth.setSpawnProxy(_point, 0);
claims.clearClaims(_point);
azimuth.cancelEscape(_point);
}
// reset sensitive data
// used when transferring the point to a new owner
//
else if ( _reset )
{
// clear the network public keys and break continuity,
// but only if the point has already been linked
//
if ( azimuth.hasBeenLinked(_point) )
{
azimuth.incrementContinuityNumber(_point);
azimuth.setKeys(_point, 0, 0, 0);
}
// clear management proxy
//
azimuth.setManagementProxy(_point, 0);
// clear voting proxy
//
azimuth.setVotingProxy(_point, 0);
// clear transfer proxy
//
// in most cases this is done above, during the ownership transfer,
// but we might not hit that and still be expected to reset the
// transfer proxy.
// doing it a second time is a no-op in Azimuth.
//
azimuth.setTransferProxy(_point, 0);
// clear spawning proxy
//
// don't clear if the spawn rights have been deposited to L2,
//
if ( depositAddress != azimuth.getSpawnProxy(_point) )
{
azimuth.setSpawnProxy(_point, 0);
}
// clear claims
//
claims.clearClaims(_point);
}
}
// escape(): request escape as _point to _sponsor
//
// if an escape request is already active, this overwrites
// the existing request
//
// Requirements:
// - :msg.sender must be the owner or manager of _point,
// - _point must be able to escape to _sponsor as per to canEscapeTo()
//
function escape(uint32 _point, uint32 _sponsor)
external
activePointManager(_point)
onL1(_point)
{
// if the sponsor is on L2, we need to escape using L2
//
require( depositAddress != azimuth.getOwner(_sponsor) );
require(canEscapeTo(_point, _sponsor));
azimuth.setEscapeRequest(_point, _sponsor);
}
// cancelEscape(): cancel the currently set escape for _point
//
function cancelEscape(uint32 _point)
external
activePointManager(_point)
{
azimuth.cancelEscape(_point);
}
// adopt(): as the relevant sponsor, accept the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function adopt(uint32 _point)
external
onL1(_point)
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// _sponsor becomes _point's sponsor
// its escape request is reset to "not escaping"
//
azimuth.doEscape(_point);
}
// reject(): as the relevant sponsor, deny the _point's request
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function reject(uint32 _point)
external
{
uint32 request = azimuth.getEscapeRequest(_point);
require( azimuth.isEscaping(_point) &&
azimuth.canManage( request, msg.sender ) );
require( depositAddress != azimuth.getOwner(request) );
// reset the _point's escape request to "not escaping"
//
azimuth.cancelEscape(_point);
}
// detach(): as the _sponsor, stop sponsoring the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's current sponsor
//
// We allow detachment even of points that are on L2. This is
// so that a star controlled by a contract can detach from a
// planet which was on L1 originally but now is on L2. L2 will
// ignore this if this is not the actual sponsor anymore (i.e. if
// they later changed their sponsor on L2).
//
function detach(uint32 _point)
external
{
uint32 sponsor = azimuth.getSponsor(_point);
require( azimuth.hasSponsor(_point) &&
azimuth.canManage(sponsor, msg.sender) );
require( depositAddress != azimuth.getOwner(sponsor) );
// signal that its sponsor no longer supports _point
//
azimuth.loseSponsor(_point);
}
//
// Point rules
//
// getSpawnLimit(): returns the total number of children the _point
// is allowed to spawn at _time.
//
function getSpawnLimit(uint32 _point, uint256 _time)
public
view
returns (uint32 limit)
{
Azimuth.Size size = azimuth.getPointSize(_point);
if ( size == Azimuth.Size.Galaxy )
{
return 255;
}
else if ( size == Azimuth.Size.Star )
{
// in 2019, stars may spawn at most 1024 planets. this limit doubles
// for every subsequent year.
//
// Note: 1546300800 corresponds to 2019-01-01
//
uint256 yearsSince2019 = (_time - 1546300800) / 365 days;
if (yearsSince2019 < 6)
{
limit = uint32( 1024 * (2 ** yearsSince2019) );
}
else
{
limit = 65535;
}
return limit;
}
else // size == Azimuth.Size.Planet
{
// planets can create moons, but moons aren't on the chain
//
return 0;
}
}
// canEscapeTo(): true if _point could try to escape to _sponsor
//
function canEscapeTo(uint32 _point, uint32 _sponsor)
public
view
returns (bool canEscape)
{
// can't escape to a sponsor that hasn't been linked
//
if ( !azimuth.hasBeenLinked(_sponsor) ) return false;
// Can only escape to a point one size higher than ourselves,
// except in the special case where the escaping point hasn't
// been linked yet -- in that case we may escape to points of
// the same size, to support lightweight invitation chains.
//
// The use case for lightweight invitations is that a planet
// owner should be able to invite their friends onto an
// Azimuth network in a two-party transaction, without a new
// star relationship.
// The lightweight invitation process works by escaping your
// own active (but never linked) point to one of your own
// points, then transferring the point to your friend.
//
// These planets can, in turn, sponsor other unlinked planets,
// so the "planet sponsorship chain" can grow to arbitrary
// length. Most users, especially deep down the chain, will
// want to improve their performance by switching to direct
// star sponsors eventually.
//
Azimuth.Size pointSize = azimuth.getPointSize(_point);
Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor);
return ( // normal hierarchical escape structure
//
( (uint8(sponsorSize) + 1) == uint8(pointSize) ) ||
//
// special peer escape
//
( (sponsorSize == pointSize) &&
//
// peer escape is only for points that haven't been linked
// yet, because it's only for lightweight invitation chains
//
!azimuth.hasBeenLinked(_point) ) );
}
//
// Permission management
//
// setManagementProxy(): configure the management proxy for _point
//
// The management proxy may perform "reversible" operations on
// behalf of the owner. This includes public key configuration and
// operations relating to sponsorship.
//
function setManagementProxy(uint32 _point, address _manager)
external
activePointManager(_point)
onL1(_point)
{
azimuth.setManagementProxy(_point, _manager);
}
// setSpawnProxy(): give _spawnProxy the right to spawn points
// with the prefix _prefix
//
// takes a uint16 so that we can't set spawn proxy for a planet
//
// fails if spawn rights have been deposited to L2
//
function setSpawnProxy(uint16 _prefix, address _spawnProxy)
external
activePointSpawner(_prefix)
onL1(_prefix)
{
require( depositAddress != azimuth.getSpawnProxy(_prefix) );
azimuth.setSpawnProxy(_prefix, _spawnProxy);
}
// setVotingProxy(): configure the voting proxy for _galaxy
//
// the voting proxy is allowed to start polls and cast votes
// on the point's behalf.
//
function setVotingProxy(uint8 _galaxy, address _voter)
external
activePointVoter(_galaxy)
{
azimuth.setVotingProxy(_galaxy, _voter);
}
// setTransferProxy(): give _transferProxy the right to transfer _point
//
// Requirements:
// - :msg.sender must be either _point's current owner,
// or be an operator for the current owner
//
function setTransferProxy(uint32 _point, address _transferProxy)
public
onL1(_point)
{
// owner: owner of _point
//
address owner = azimuth.getOwner(_point);
// caller must be :owner, or an operator designated by the owner.
//
require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));
// set transfer proxy field in Azimuth contract
//
azimuth.setTransferProxy(_point, _transferProxy);
// emit Approval event
//
emit Approval(owner, _transferProxy, uint256(_point));
}
//
// Poll actions
//
// startUpgradePoll(): as _galaxy, start a poll for the ecliptic
// upgrade _proposal
//
// Requirements:
// - :msg.sender must be the owner or voting proxy of _galaxy,
// - the _proposal must expect to be upgraded from this specific
// contract, as indicated by its previousEcliptic attribute
//
function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal)
external
activePointVoter(_galaxy)
{
// ensure that the upgrade target expects this contract as the source
//
require(_proposal.previousEcliptic() == address(this));
polls.startUpgradePoll(_proposal);
}
// startDocumentPoll(): as _galaxy, start a poll for the _proposal
//
// the _proposal argument is the keccak-256 hash of any arbitrary
// document or string of text
//
function startDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
activePointVoter(_galaxy)
{
polls.startDocumentPoll(_proposal);
}
// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic
// upgrade _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
// If this vote results in a majority for the _proposal, it will
// be upgraded to immediately.
//
function castUpgradeVote(uint8 _galaxy,
EclipticBase _proposal,
bool _vote)
external
activePointVoter(_galaxy)
{
// majority: true if the vote resulted in a majority, false otherwise
//
bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// castDocumentVote(): as _galaxy, cast a _vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote)
external
activePointVoter(_galaxy)
{
polls.castDocumentVote(_galaxy, _proposal, _vote);
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, upgrading to it if it has
//
function updateUpgradePoll(EclipticBase _proposal)
external
{
// majority: true if the poll ended in a majority, false otherwise
//
bool majority = polls.updateUpgradePoll(_proposal);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// updateDocumentPoll(): check whether the _proposal has achieved majority
//
// Note: the polls contract publicly exposes the function this calls,
// but we offer it in the ecliptic interface as a convenience
//
function updateDocumentPoll(bytes32 _proposal)
external
{
polls.updateDocumentPoll(_proposal);
}
// upgradeTreasury: upgrade implementation for treasury
//
// Note: we specify when deploying Ecliptic the keccak hash
// of the implementation we're upgrading to
//
function upgradeTreasury(address _treasuryImpl) external {
require(!treasuryUpgraded);
require(keccak256(_treasuryImpl) == treasuryUpgradeHash);
treasuryProxy.upgradeTo(_treasuryImpl);
treasuryUpgraded = true;
}
//
// Contract owner operations
//
// createGalaxy(): grant _target ownership of the _galaxy and register
// it for voting
//
function createGalaxy(uint8 _galaxy, address _target)
external
onlyOwner
{
// only currently unowned (and thus also inactive) galaxies can be
// created, and only to non-zero addresses
//
require( azimuth.isOwner(_galaxy, 0x0) &&
0x0 != _target );
// new galaxy means a new registered voter
//
polls.incrementTotalVoters();
// if the caller is sending the galaxy to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_galaxy, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern,
// making the caller the owner in the mean time
//
else
{
doSpawn(_galaxy, _target, false, msg.sender);
}
}
function setDnsDomains(string _primary, string _secondary, string _tertiary)
external
onlyOwner
{
azimuth.setDnsDomains(_primary, _secondary, _tertiary);
}
//
// Function modifiers for this contract
//
// validPointId(): require that _id is a valid point
//
modifier validPointId(uint256 _id)
{
require(_id < 0x100000000);
_;
}
// onL1(): require that ship is not deposited
modifier onL1(uint32 _point)
{
require( depositAddress != azimuth.getOwner(_point) );
_;
}
}
|
startUpgradePoll(): open a poll on making _proposal the new ecliptic _proposal must not have achieved majority before if the proposal is being made for the first time, register it.
|
function startUpgradePoll(address _proposal)
external
onlyOwner
{
require(!upgradeHasAchievedMajority[_proposal]);
Poll storage poll = upgradePolls[_proposal];
if (0 == poll.start)
{
upgradeProposals.push(_proposal);
}
startPoll(poll);
emit UpgradePollStarted(_proposal);
}
| 1,053,656 |
./partial_match/1/0xC8B4a74F7685e901D3c57a5Ec37aF8Ad450d8784/sources/PROGENS.sol
|
Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `account` cannot be the zero address./
|
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_Allowances[account] = _Allowances[account].add(amount);
emit Transfer(address(0), account, amount);
}
| 4,078,474 |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization
* control functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the
* sender account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC223
* @dev ERC223 contract interface with ERC20 functions and events
* Fully backward compatible with ERC20
* Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended
*/
contract ERC223 {
uint public totalSupply;
// ERC223 and ERC20 functions and events
function balanceOf(address who) public view returns (uint);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
// ERC223 functions
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
// ERC20 functions and events
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title ContractReceiver
* @dev Contract that is working with ERC223 tokens
*/
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
/**
* tkn variable is analogue of msg variable of Ether transaction
* tkn.sender is person who initiated this token transaction (analogue of msg.sender)
* tkn.value the number of tokens that were sent (analogue of msg.value)
* tkn.data is data of token transaction (analogue of msg.data)
* tkn.sig is 4 bytes signature of function if data of token transaction is a function execution
*/
}
}
/**
* @title Alpon
* @author Alpon
* @dev Alpon is an ERC223 Token with ERC20 functions and events
* Fully backward compatible with ERC20
*/
contract Alpon is ERC223, Ownable {
using SafeMath for uint256;
string public name = "Alpon";
string public symbol = "APN";
uint8 public decimals = 8;
uint256 public initialSupply = 10e9 * 1e8;
uint256 public totalSupply;
uint256 public distributeAmount = 0;
bool public mintingFinished = false;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public unlockUnixTime;
event FrozenFunds(address indexed target, bool frozen);
event LockedFunds(address indexed target, uint256 locked);
event Burn(address indexed from, uint256 amount);
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @dev Constructor is called only once and can not be called again
*/
function Alpon() public {
totalSupply = initialSupply;
balanceOf[msg.sender] = totalSupply;
}
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOf[_owner];
}
/**
* @dev Prevent targets from sending or receiving tokens
* @param targets Addresses to be frozen
* @param isFrozen either to freeze it or not
*/
function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public {
require(targets.length > 0);
for (uint j = 0; j < targets.length; j++) {
require(targets[j] != 0x0);
frozenAccount[targets[j]] = isFrozen;
FrozenFunds(targets[j], isFrozen);
}
}
/**
* @dev Prevent targets from sending or receiving tokens by setting Unix times
* @param targets Addresses to be locked funds
* @param unixTimes Unix times when locking up will be finished
*/
function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public {
require(targets.length > 0
&& targets.length == unixTimes.length);
for(uint j = 0; j < targets.length; j++){
require(unlockUnixTime[targets[j]] < unixTimes[j]);
unlockUnixTime[targets[j]] = unixTimes[j];
LockedFunds(targets[j], unixTimes[j]);
}
}
/**
* @dev Function that is called when a user or another contract wants to transfer funds
*/
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
if (isContract(_to)) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
/**
* @dev Standard function transfer similar to ERC20 transfer with no _data
* Added due to backwards compatibility reasons
*/
function transfer(address _to, uint _value) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private 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);
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* Added due to backwards compatibility with ERC20
* @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 success) {
require(_to != address(0)
&& _value > 0
&& balanceOf[_from] >= _value
&& allowance[_from][msg.sender] >= _value
&& frozenAccount[_from] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[_from]
&& now > unlockUnixTime[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Allows _spender to spend no more than _value tokens in your behalf
* Added due to backwards compatibility with ERC20
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender
* Added due to backwards compatibility with ERC20
* @param _owner address The address which owns the funds
* @param _spender address The address which will spend the funds
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowance[_owner][_spender];
}
/**
* @dev Burns a specific amount of tokens.
* @param _from The address that will burn the tokens.
* @param _unitAmount The amount of token to be burned.
*/
function burn(address _from, uint256 _unitAmount) onlyOwner public {
require(_unitAmount > 0
&& balanceOf[_from] >= _unitAmount);
balanceOf[_from] = balanceOf[_from].sub(_unitAmount);
totalSupply = totalSupply.sub(_unitAmount);
Burn(_from, _unitAmount);
}
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _unitAmount The amount of tokens to mint.
*/
function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) {
require(_unitAmount > 0);
totalSupply = totalSupply.add(_unitAmount);
balanceOf[_to] = balanceOf[_to].add(_unitAmount);
Mint(_to, _unitAmount);
Transfer(address(0), _to, _unitAmount);
return true;
}
/**
* @dev Function to stop minting new tokens.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
/**
* @dev Function to distribute tokens to the list of addresses by the provided amount.
*/
function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) {
require(amount > 0
&& addresses.length > 0
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
amount = amount.mul(1e8);
uint256 totalAmount = amount.mul(addresses.length);
require(balanceOf[msg.sender] >= totalAmount);
for (uint j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount);
Transfer(msg.sender, addresses[j], amount);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) {
require(addresses.length > 0
&& addresses.length == amounts.length
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0
&& addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
amounts[j] = amounts[j].mul(1e8);
totalAmount = totalAmount.add(amounts[j]);
}
require(balanceOf[msg.sender] >= totalAmount);
for (j = 0; j < addresses.length; j++) {
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
Transfer(msg.sender, addresses[j], amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0
&& addresses.length == amounts.length);
uint256 totalAmount = 0;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0
&& addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
amounts[j] = amounts[j].mul(1e8);
require(balanceOf[addresses[j]] >= amounts[j]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
Transfer(addresses[j], msg.sender, amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount);
return true;
}
function setDistributeAmount(uint256 _unitAmount) onlyOwner public {
distributeAmount = _unitAmount;
}
/**
* @dev Function to distribute tokens to the msg.sender automatically
* If distributeAmount is 0, this function doesn't work
*/
function autoDistribute() payable public {
require(distributeAmount > 0
&& balanceOf[owner] >= distributeAmount
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
if(msg.value > 0) owner.transfer(msg.value);
balanceOf[owner] = balanceOf[owner].sub(distributeAmount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount);
Transfer(owner, msg.sender, distributeAmount);
}
/**
* @dev fallback function
*/
function() payable public {
autoDistribute();
}
}
|
Constructor is called only once and can not be called again/
|
function Alpon() public {
totalSupply = initialSupply;
balanceOf[msg.sender] = totalSupply;
}
| 10,867,915 |
./full_match/1/0x7af62458e41E2F490D2Df54A8FeDc56fFedB8c17/sources/lib/solady/src/tokens/ERC721.sol
|
Transfers token `id` from `from` to `to`. Requirements: - Token `id` must exist. - `from` must be the owner of the token. - `to` cannot be the zero address. - The caller must be the owner of the token, or be approved to manage the token. - 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 id, bytes memory data)
internal
virtual
{
_transfer(address(0), from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
| 3,202,338 |
./partial_match/4/0x5C232702e1EF72e81e53f198631A36105Eb8805d/sources/ExchangeDataStore.sol
|
setTickeData use for “tickers” data (prices of cryptocurrencies in different exchanges) hash every 24 hours or less, and record those hashes _rowHashID hash for last id/ require(isIssuer[msg.sender] == true, "Issuer not registered to register a certificate"); require(isRecipient[_recipient] == true, "Recipient not registered to be issued a certificate"); require(issuerOfCertificate[certificate_hash] == msg.sender, "Issuer not registered to issue this certificate");
|
function setTickeData(string memory _rowHashID,string memory _rowTickerHash) public {
TickerData memory ticker;
uint id = ++tickerData_counter;
ticker.rowTickerHash = _rowTickerHash;
ticker.rowHashID = _rowHashID;
ticker.creationDate = block.timestamp;
ticker.createByAddress = msg.sender;
tickerDataIdentifier[id] = ticker;
hashTickerData[_rowTickerHash] = true;
TickerDataByID[_rowHashID] = ticker;
emit TickerDataAdd(id, msg.sender, _rowHashID, _rowTickerHash);
}
| 8,760,412 |
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.24;
/**
* @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: openzeppelin-solidity/contracts/math/SafeMath.sol
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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
pragma solidity ^0.4.24;
/**
* @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: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @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
pragma solidity ^0.4.24;
/**
* @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: openzeppelin-solidity/contracts/ownership/Ownable.sol
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;
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/base/MintableToken.sol
pragma solidity ^0.4.24;
/**
* @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)
{
return _mint(_to, _amount);
}
/**
* @dev Internal 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
)
internal
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: openzeppelin-solidity/contracts/lifecycle/Destructible.sol
pragma solidity ^0.4.24;
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.24;
/**
* @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: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
pragma solidity ^0.4.24;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
pragma solidity ^0.4.24;
/**
* @title DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: openzeppelin-solidity/contracts/access/rbac/Roles.sol
pragma solidity ^0.4.24;
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
// File: openzeppelin-solidity/contracts/access/rbac/RBAC.sol
pragma solidity ^0.4.24;
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: openzeppelin-solidity/contracts/access/Whitelist.sol
pragma solidity ^0.4.24;
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: openzeppelin-solidity/contracts/ECRecovery.sol
pragma solidity ^0.4.24;
/**
* @title Elliptic 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:"
* 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(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
);
}
}
// File: contracts/SilverToken.sol
pragma solidity ^0.4.24;
interface ASilverDollar {
function purchaseWithSilverToken(address, uint256) external returns(bool);
}
contract SilverToken is Destructible, Pausable, MintableToken, BurnableToken, DetailedERC20("Silvertoken", "SLVT", 8), Whitelist {
using SafeMath for uint256;
using ECRecovery for bytes32;
uint256 public transferFee = 10;//1%
uint256 public transferDiscountFee = 8;//0.8%
uint256 public redemptionFee = 40;//4%
uint256 public convertFee = 10;//1%
address public feeReturnAddress = 0xE34f13B2dadC938f44eCbC38A8dBe94B8bdB2109;
uint256 public transferFreeAmount;
uint256 public transferDiscountAmount;
address public silverDollarAddress;
address public SLVTReserve = 0x900122447a2Eaeb1655C99A91E20f506D509711B;
bool public canPurchase = true;
bool public canConvert = true;
// Internal features
uint256 internal multiplier;
uint256 internal percentage = 1000;
//ce4385affa8ad2cbec45b1660c6f6afcb691bf0a7a73ebda096ee1dfb670fe6f
event TokenRedeemed(address from, uint256 amount);
//3ceffd410054fdaed44f598ff5c1fb450658778e2241892da4aa646979dee617
event TokenPurchased(address addr, uint256 amount, uint256 tokens);
//5a56a31cc0c9ebf5d0626c5189b951fe367d953afc1824a8bb82bf168713cc52
event FeeApplied(string name, address addr, uint256 amount);
event Converted(address indexed sender, uint256 amountSLVT, uint256 amountSLVD, uint256 amountFee);
modifier purchasable() {
require(canPurchase == true, "can't purchase");
_;
}
modifier onlySilverDollar() {
require(msg.sender == silverDollarAddress, "not silverDollar");
_;
}
modifier isConvertible() {
require(canConvert == true, "SLVT conversion disabled");
_;
}
constructor () public {
multiplier = 10 ** uint256(decimals);
transferFreeAmount = 2 * multiplier;
transferDiscountAmount = 500 * multiplier;
owner = msg.sender;
super.mint(msg.sender, 1 * 1000 * 1000 * multiplier);
}
// Settings begin
function setTransferFreeAmount(uint256 value) public onlyOwner { transferFreeAmount = value; }
function setTransferDiscountAmount(uint256 value) public onlyOwner { transferDiscountAmount = value; }
function setRedemptionFee(uint256 value) public onlyOwner { redemptionFee = value; }
function setFeeReturnAddress(address value) public onlyOwner { feeReturnAddress = value; }
function setCanPurchase(bool value) public onlyOwner { canPurchase = value; }
function setSilverDollarAddress(address value) public onlyOwner { silverDollarAddress = value; }
function setCanConvert(bool value) public onlyOwner { canConvert = value; }
function setConvertFee(uint256 value) public onlyOwner { convertFee = value; }
function increaseTotalSupply(uint256 value) public onlyOwner returns (uint256) {
super.mint(owner, value);
return totalSupply_;
}
// Settings end
// ERC20 re-implementation methods begin
function transfer(address to, uint256 amount) public whenNotPaused returns (bool) {
uint256 feesPaid = payFees(address(0), to, amount);
require(super.transfer(to, amount.sub(feesPaid)), "failed transfer");
return true;
}
function transferFrom(address from, address to, uint256 amount) public whenNotPaused returns (bool) {
uint256 feesPaid = payFees(from, to, amount);
require(super.transferFrom(from, to, amount.sub(feesPaid)), "failed transferFrom");
return true;
}
// ERC20 re-implementation methods end
// Silvertoken methods end
function payFees(address from, address to, uint256 amount) private returns (uint256 fees) {
if (msg.sender == owner || hasRole(from, ROLE_WHITELISTED) || hasRole(msg.sender, ROLE_WHITELISTED) || hasRole(to, ROLE_WHITELISTED))
return 0;
fees = getTransferFee(amount);
if (from == address(0)) {
require(super.transfer(feeReturnAddress, fees), "transfer fee payment failed");
}
else {
require(super.transferFrom(from, feeReturnAddress, fees), "transferFrom fee payment failed");
}
emit FeeApplied("Transfer", to, fees);
}
function getTransferFee(uint256 amount) internal view returns(uint256) {
if (transferFreeAmount > 0 && amount <= transferFreeAmount) return 0;
if (transferDiscountAmount > 0 && amount >= transferDiscountAmount) return amount.mul(transferDiscountFee).div(percentage);
return amount.mul(transferFee).div(percentage);
}
function transferTokens(address from, address to, uint256 amount) internal returns (bool) {
require(balances[from] >= amount, "balance insufficient");
balances[from] = balances[from].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(from, to, amount);
return true;
}
function purchase(uint256 tokens, uint256 fee, uint256 timestamp, bytes signature) public payable purchasable whenNotPaused {
require(
isSignatureValid(
msg.sender, msg.value, tokens, fee, timestamp, signature
),
"invalid signature"
);
require(tokens > 0, "invalid number of tokens");
emit TokenPurchased(msg.sender, msg.value, tokens);
transferTokens(owner, msg.sender, tokens);
feeReturnAddress.transfer(msg.value);
if (fee > 0) {
emit FeeApplied("Purchase", msg.sender, fee);
}
}
function purchasedSilverDollar(uint256 amount) public onlySilverDollar purchasable whenNotPaused returns (bool) {
require(super._mint(SLVTReserve, amount), "minting of slvT failed");
return true;
}
function purchaseWithSilverDollar(address to, uint256 amount) public onlySilverDollar purchasable whenNotPaused returns (bool) {
require(transferTokens(SLVTReserve, to, amount), "failed transfer of slvT from reserve");
return true;
}
function redeem(uint256 tokens) public whenNotPaused {
require(tokens > 0, "amount of tokens redeemed must be > 0");
uint256 fee = tokens.mul(redemptionFee).div(percentage);
_burn(msg.sender, tokens.sub(fee));
if (fee > 0) {
require(super.transfer(feeReturnAddress, fee), "token transfer failed");
emit FeeApplied("Redeem", msg.sender, fee);
}
emit TokenRedeemed(msg.sender, tokens);
}
function isSignatureValid(
address sender, uint256 amount, uint256 tokens,
uint256 fee, uint256 timestamp, bytes signature
) public view returns (bool)
{
if (block.timestamp > timestamp + 10 minutes) return false;
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
sender,
amount,
tokens,
fee,
timestamp
)
);
return hash.toEthSignedMessageHash().recover(signature) == owner;
}
function isConvertSignatureValid(
address sender, uint256 amountSLVT, uint256 amountSLVD,
uint256 timestamp, bytes signature
) public view returns (bool)
{
if (block.timestamp > timestamp + 10 minutes) return false;
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
sender,
amountSLVT,
amountSLVD,
timestamp
)
);
return hash.toEthSignedMessageHash().recover(signature) == owner;
}
function convertToSLVD(
uint256 amountSLVT, uint256 amountSLVD,
uint256 timestamp, bytes signature
) public isConvertible whenNotPaused returns (bool) {
require(
isConvertSignatureValid(
msg.sender, amountSLVT,
amountSLVD, timestamp, signature
),
"convert failed, invalid signature"
);
uint256 fees = amountSLVT.mul(convertFee).div(percentage);
if (whitelist(msg.sender) && Whitelist(silverDollarAddress).whitelist(msg.sender))
fees = 0;
super.transfer(SLVTReserve, amountSLVT.sub(fees));
require(super.transfer(feeReturnAddress, fees), "transfer fee payment failed");
require(
ASilverDollar(silverDollarAddress).purchaseWithSilverToken(msg.sender, amountSLVD),
"failed purchase of silverdollar with silvertoken"
);
emit Converted(msg.sender, amountSLVD, amountSLVD, fees);
return true;
}
}
|
remove an address from the whitelist _operator address return true if the address was removed from the whitelist, false if the address wasn't in the whitelist in the first place/
|
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
| 969,431 |
/**
*Submitted for verification at Etherscan.io on 2021-02-23
*/
pragma solidity 0.6.12;
interface marketManagerInterface {
function setBreakerTable(address _target, bool _status) external returns (bool);
function getCircuitBreaker() external view returns (bool);
function setCircuitBreaker(bool _emergency) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory);
function handlerRegister(uint256 handlerID, address tokenHandlerAddr) external returns (bool);
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256);
function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function getTokenHandlersLength() external view returns (uint256);
function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256);
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256);
function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256);
function setLiquidationManager(address liquidationManagerAddr) external returns (bool);
function rewardClaimAll(address payable userAddr) external returns (bool);
function updateRewardParams(address payable userAddr) external returns (bool);
function interestUpdateReward() external returns (bool);
function getGlobalRewardInfo() external view returns (uint256, uint256, uint256);
function setOracleProxy(address oracleProxyAddr) external returns (bool);
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool);
function ownerRewardTransfer(uint256 _amount) external returns (bool);
}
pragma solidity 0.6.12;
interface managerDataStorageInterface {
function getGlobalRewardPerBlock() external view returns (uint256);
function setGlobalRewardPerBlock(uint256 _globalRewardPerBlock) external returns (bool);
function getGlobalRewardDecrement() external view returns (uint256);
function setGlobalRewardDecrement(uint256 _globalRewardDecrement) external returns (bool);
function getGlobalRewardTotalAmount() external view returns (uint256);
function setGlobalRewardTotalAmount(uint256 _globalRewardTotalAmount) external returns (bool);
function getAlphaRate() external view returns (uint256);
function setAlphaRate(uint256 _alphaRate) external returns (bool);
function getAlphaLastUpdated() external view returns (uint256);
function setAlphaLastUpdated(uint256 _alphaLastUpdated) external returns (bool);
function getRewardParamUpdateRewardPerBlock() external view returns (uint256);
function setRewardParamUpdateRewardPerBlock(uint256 _rewardParamUpdateRewardPerBlock) external returns (bool);
function getRewardParamUpdated() external view returns (uint256);
function setRewardParamUpdated(uint256 _rewardParamUpdated) external returns (bool);
function getInterestUpdateRewardPerblock() external view returns (uint256);
function setInterestUpdateRewardPerblock(uint256 _interestUpdateRewardPerblock) external returns (bool);
function getInterestRewardUpdated() external view returns (uint256);
function setInterestRewardUpdated(uint256 _interestRewardLastUpdated) external returns (bool);
function setTokenHandler(uint256 handlerID, address handlerAddr) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerAddr(uint256 handlerID) external view returns (address);
function setTokenHandlerAddr(uint256 handlerID, address handlerAddr) external returns (bool);
function getTokenHandlerExist(uint256 handlerID) external view returns (bool);
function setTokenHandlerExist(uint256 handlerID, bool exist) external returns (bool);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function setTokenHandlerSupport(uint256 handlerID, bool support) external returns (bool);
function setLiquidationManagerAddr(address _liquidationManagerAddr) external returns (bool);
function getLiquidationManagerAddr() external view returns (address);
function setManagerAddr(address _managerAddr) external returns (bool);
}
// File: contracts/interfaces/marketHandlerInterface.sol
pragma solidity 0.6.12;
interface marketHandlerInterface {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setCircuitBreakWithOwner(bool _emergency) external returns (bool);
function getTokenName() external view returns (string memory);
function ownershipTransfer(address payable newOwner) external returns (bool);
function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256);
function getTokenHandlerLimit() external view returns (uint256, uint256);
function getTokenHandlerBorrowLimit() external view returns (uint256);
function getTokenHandlerMarginCallLimit() external view returns (uint256);
function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool);
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool);
function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256);
function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256);
function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256);
function checkFirstAction() external returns (bool);
function applyInterest(address payable userAddr) external returns (uint256, uint256);
function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool);
function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function getSIRandBIR() external view returns (uint256, uint256);
}
// File: contracts/interfaces/oracleProxyInterface.sol
pragma solidity 0.6.12;
interface oracleProxyInterface {
function getTokenPrice(uint256 tokenID) external view returns (uint256);
function getOracleFeed(uint256 tokenID) external view returns (address, uint256);
function setOracleFeed(uint256 tokenID, address feedAddr, uint256 decimals) external returns (bool);
}
// File: contracts/interfaces/liquidationManagerInterface.sol
pragma solidity 0.6.12;
interface liquidationManagerInterface {
function setCircuitBreaker(bool _emergency) external returns (bool);
function partialLiquidation(address payable delinquentBorrower, uint256 targetHandler, uint256 liquidateAmount, uint256 receiveHandler) external returns (uint256);
function checkLiquidation(address payable userAddr) external view returns (bool);
}
// File: contracts/interfaces/proxyContractInterface.sol
pragma solidity 0.6.12;
interface proxyContractInterface {
function handlerProxy(bytes memory data) external returns (bool, bytes memory);
function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory);
function siProxy(bytes memory data) external returns (bool, bytes memory);
function siViewProxy(bytes memory data) external view returns (bool, bytes memory);
}
// File: contracts/interfaces/tokenInterface.sol
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external ;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external view returns (bool);
function transferFrom(address from, address to, uint256 value) external ;
}
// File: contracts/Errors.sol
pragma solidity 0.6.12;
contract Modifier {
string internal constant ONLY_OWNER = "O";
string internal constant ONLY_MANAGER = "M";
string internal constant CIRCUIT_BREAKER = "emergency";
}
contract ManagerModifier is Modifier {
string internal constant ONLY_HANDLER = "H";
string internal constant ONLY_LIQUIDATION_MANAGER = "LM";
string internal constant ONLY_BREAKER = "B";
}
contract HandlerDataStorageModifier is Modifier {
string internal constant ONLY_BIFI_CONTRACT = "BF";
}
contract SIDataStorageModifier is Modifier {
string internal constant ONLY_SI_HANDLER = "SI";
}
contract HandlerErrors is Modifier {
string internal constant USE_VAULE = "use value";
string internal constant USE_ARG = "use arg";
string internal constant EXCEED_LIMIT = "exceed limit";
string internal constant NO_LIQUIDATION = "no liquidation";
string internal constant NO_LIQUIDATION_REWARD = "no enough reward";
string internal constant NO_EFFECTIVE_BALANCE = "not enough balance";
string internal constant TRANSFER = "err transfer";
}
contract SIErrors is Modifier { }
contract InterestErrors is Modifier { }
contract LiquidationManagerErrors is Modifier {
string internal constant NO_DELINQUENT = "not delinquent";
}
contract ManagerErrors is ManagerModifier {
string internal constant REWARD_TRANSFER = "RT";
string internal constant UNSUPPORTED_TOKEN = "UT";
}
contract OracleProxyErrors is Modifier {
string internal constant ZERO_PRICE = "price zero";
}
contract RequestProxyErrors is Modifier { }
contract ManagerDataStorageErrors is ManagerModifier {
string internal constant NULL_ADDRESS = "err addr null";
}
// File: contracts/SafeMath.sol
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
pragma solidity ^0.6.12;
library SafeMath {
uint256 internal constant unifiedPoint = 10 ** 18;
/******************** Safe Math********************/
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "a");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "s");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "d");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a* b;
require((c / a) == b, "m");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "d");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "m");
}
}
// File: contracts/marketManager/tokenManager.sol
pragma solidity 0.6.12;
/**
* @title Bifi's marketManager contract
* @notice Implement business logic and manage handlers
* @author Bifi
*/
contract etherManager is marketManagerInterface, ManagerErrors {
using SafeMath for uint256;
address public owner;
bool public emergency = false;
managerDataStorageInterface internal dataStorageInstance;
oracleProxyInterface internal oracleProxy;
/* feat: manager reward token instance*/
IERC20 internal rewardErc20Instance;
string internal constant updateRewardLane = "updateRewardLane(address)";
mapping(address => Breaker) internal breakerTable;
struct UserAssetsInfo {
uint256 depositAssetSum;
uint256 borrowAssetSum;
uint256 marginCallLimitSum;
uint256 depositAssetBorrowLimitSum;
uint256 depositAsset;
uint256 borrowAsset;
uint256 price;
uint256 callerPrice;
uint256 depositAmount;
uint256 borrowAmount;
uint256 borrowLimit;
uint256 marginCallLimit;
uint256 callerBorrowLimit;
uint256 userBorrowableAsset;
uint256 withdrawableAsset;
}
struct Breaker {
bool auth;
bool tried;
}
struct HandlerInfo {
bool support;
address addr;
proxyContractInterface tokenHandler;
bytes data;
}
uint256 public tokenHandlerLength;
modifier onlyOwner {
require(msg.sender == owner, ONLY_OWNER);
_;
}
modifier onlyHandler(uint256 handlerID) {
_isHandler(handlerID);
_;
}
function _isHandler(uint256 handlerID) internal view {
address msgSender = msg.sender;
require((msgSender == dataStorageInstance.getTokenHandlerAddr(handlerID)) || (msgSender == owner), ONLY_HANDLER);
}
modifier onlyLiquidationManager {
_isLiquidationManager();
_;
}
function _isLiquidationManager() internal view {
address msgSender = msg.sender;
require((msgSender == dataStorageInstance.getLiquidationManagerAddr()) || (msgSender == owner), ONLY_LIQUIDATION_MANAGER);
}
modifier circuitBreaker {
_isCircuitBreak();
_;
}
function _isCircuitBreak() internal view {
require((!emergency) || (msg.sender == owner), CIRCUIT_BREAKER);
}
modifier onlyBreaker {
_isBreaker();
_;
}
function _isBreaker() internal view {
require(breakerTable[msg.sender].auth, ONLY_BREAKER);
}
/**
* @dev Constructor for marketManager
* @param managerDataStorageAddr The address of the manager storage contract
* @param oracleProxyAddr The address of oracle proxy contract (e.g., price feeds)
* @param breaker The address of default circuit breaker
* @param erc20Addr The address of reward token (ERC-20)
*/
constructor (address managerDataStorageAddr, address oracleProxyAddr, address breaker, address erc20Addr) public
{
owner = msg.sender;
dataStorageInstance = managerDataStorageInterface(managerDataStorageAddr);
oracleProxy = oracleProxyInterface(oracleProxyAddr);
rewardErc20Instance = IERC20(erc20Addr);
breakerTable[owner].auth = true;
breakerTable[breaker].auth = true;
}
/**
* @dev Transfer ownership
* @param _owner the address of the new owner
* @return true (TODO: validate results)
*/
function ownershipTransfer(address payable _owner) onlyOwner public returns (bool)
{
owner = _owner;
return true;
}
/**
* @dev Set the address of oracleProxy contract
* @param oracleProxyAddr The address of oracleProxy contract
* @return true (TODO: validate results)
*/
function setOracleProxy(address oracleProxyAddr) onlyOwner external override returns (bool)
{
oracleProxy = oracleProxyInterface(oracleProxyAddr);
return true;
}
/**
* @dev Set the address of BiFi reward token contract
* @param erc20Addr The address of BiFi reward token contract
* @return true (TODO: validate results)
*/
function setRewardErc20(address erc20Addr) onlyOwner public returns (bool)
{
rewardErc20Instance = IERC20(erc20Addr);
return true;
}
/**
* @dev Authorize admin user for circuitBreaker
* @param _target The address of the circuitBreaker admin user.
* @param _status The boolean status of circuitBreaker (on/off)
* @return true (TODO: validate results)
*/
function setBreakerTable(address _target, bool _status) onlyOwner external override returns (bool)
{
breakerTable[_target].auth = _status;
return true;
}
/**
* @dev Set circuitBreak to freeze/unfreeze all handlers
* @param _emergency The boolean status of circuitBreaker (on/off)
* @return true (TODO: validate results)
*/
function setCircuitBreaker(bool _emergency) onlyBreaker external override returns (bool)
{
bytes memory data;
for (uint256 handlerID = 0; handlerID < tokenHandlerLength; handlerID++)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
proxyContractInterface tokenHandler = proxyContractInterface(tokenHandlerAddr);
// use delegate call via handler proxy
// for token handlers
bytes memory callData = abi.encodeWithSignature("setCircuitBreaker(bool)", _emergency);
tokenHandler.handlerProxy(callData);
tokenHandler.siProxy(callData);
}
address liquidationManagerAddr = dataStorageInstance.getLiquidationManagerAddr();
liquidationManagerInterface liquidationManager = liquidationManagerInterface(liquidationManagerAddr);
liquidationManager.setCircuitBreaker(_emergency);
emergency = _emergency;
return true;
}
/**
* @dev Get the circuitBreak status
* @return The circuitBreak status
*/
function getCircuitBreaker() external view override returns (bool)
{
return emergency;
}
/**
* @dev Get information for a handler
* @param handlerID Handler ID
* @return (success or failure, handler address, handler name)
*/
function getTokenHandlerInfo(uint256 handlerID) external view override returns (bool, address, string memory)
{
bool support;
address tokenHandlerAddr;
string memory tokenName;
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
proxyContractInterface tokenHandler = proxyContractInterface(tokenHandlerAddr);
bytes memory data;
(, data) = tokenHandler.handlerViewProxy(abi.encodeWithSignature("getTokenName()"));
tokenName = abi.decode(data, (string));
support = true;
}
return (support, tokenHandlerAddr, tokenName);
}
/**
* @dev Register a handler
* @param handlerID Handler ID and address
* @param tokenHandlerAddr The handler address
* @return true (TODO: validate results)
*/
function handlerRegister(uint256 handlerID, address tokenHandlerAddr) onlyOwner external override returns (bool)
{
return _handlerRegister(handlerID, tokenHandlerAddr);
}
/**
* @dev Set a liquidation manager contract
* @param liquidationManagetAddr The address of liquidiation manager
* @return true (TODO: validate results)
*/
function setLiquidationManager(address liquidationManagetAddr) onlyOwner external override returns (bool)
{
dataStorageInstance.setLiquidationManagerAddr(liquidationManagetAddr);
return true;
}
/**
* @dev Update the (SI) rewards for a user
* @param userAddr The address of the user
* @param callerID The handler ID
* @return true (TODO: validate results)
*/
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external override returns (bool)
{
HandlerInfo memory handlerInfo;
(handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID);
if (handlerInfo.support)
{
proxyContractInterface tokenHandler;
tokenHandler = proxyContractInterface(handlerInfo.addr);
tokenHandler.siProxy(abi.encodeWithSignature(updateRewardLane, userAddr));
}
return true;
}
/**
* @dev Update interest of a user for a handler (internal)
* @param userAddr The user address
* @param callerID The handler ID
* @param allFlag Flag for the full calculation mode (calculting for all handlers)
* @return (uint256, uint256, uint256, uint256, uint256, uint256)
*/
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external override returns (uint256, uint256, uint256, uint256, uint256, uint256)
{
UserAssetsInfo memory userAssetsInfo;
HandlerInfo memory handlerInfo;
oracleProxyInterface _oracleProxy = oracleProxy;
managerDataStorageInterface _dataStorage = dataStorageInstance;
/* From all handlers, get the token price, margin call limit, borrow limit */
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
(handlerInfo.support, handlerInfo.addr) = _dataStorage.getTokenHandlerInfo(handlerID);
if (handlerInfo.support)
{
handlerInfo.tokenHandler = proxyContractInterface(handlerInfo.addr);
/* If the full-calculation mode is not set, work on the given handler only */
if ((handlerID == callerID) || allFlag)
{
handlerInfo.tokenHandler.siProxy( abi.encodeWithSignature("updateRewardLane(address)", userAddr) );
(, handlerInfo.data) = handlerInfo.tokenHandler.handlerProxy( abi.encodeWithSignature("applyInterest(address)", userAddr) );
(userAssetsInfo.depositAmount, userAssetsInfo.borrowAmount) = abi.decode(handlerInfo.data, (uint256, uint256));
}
else
{
/* Get the deposit and borrow amount for the user */
(, handlerInfo.data) = handlerInfo.tokenHandler.handlerViewProxy( abi.encodeWithSignature("getUserAmount(address)", userAddr) );
(userAssetsInfo.depositAmount, userAssetsInfo.borrowAmount) = abi.decode(handlerInfo.data, (uint256, uint256));
}
(, handlerInfo.data) = handlerInfo.tokenHandler.handlerViewProxy( abi.encodeWithSignature("getTokenHandlerLimit()") );
(userAssetsInfo.borrowLimit, userAssetsInfo.marginCallLimit) = abi.decode(handlerInfo.data, (uint256, uint256));
/* Get the token price */
if (handlerID == callerID)
{
userAssetsInfo.price = _oracleProxy.getTokenPrice(handlerID);
userAssetsInfo.callerPrice = userAssetsInfo.price;
userAssetsInfo.callerBorrowLimit = userAssetsInfo.borrowLimit;
}
/* If the user has no balance, the token handler can be ignored.*/
if ((userAssetsInfo.depositAmount > 0) || (userAssetsInfo.borrowAmount > 0))
{
if (handlerID != callerID)
{
userAssetsInfo.price = _oracleProxy.getTokenPrice(handlerID);
}
/* Compute the deposit parameters */
if (userAssetsInfo.depositAmount > 0)
{
userAssetsInfo.depositAsset = userAssetsInfo.depositAmount.unifiedMul(userAssetsInfo.price);
userAssetsInfo.depositAssetBorrowLimitSum = userAssetsInfo.depositAssetBorrowLimitSum.add(userAssetsInfo.depositAsset.unifiedMul(userAssetsInfo.borrowLimit));
userAssetsInfo.marginCallLimitSum = userAssetsInfo.marginCallLimitSum.add(userAssetsInfo.depositAsset.unifiedMul(userAssetsInfo.marginCallLimit));
userAssetsInfo.depositAssetSum = userAssetsInfo.depositAssetSum.add(userAssetsInfo.depositAsset);
}
/* Compute the borrow parameters */
if (userAssetsInfo.borrowAmount > 0)
{
userAssetsInfo.borrowAsset = userAssetsInfo.borrowAmount.unifiedMul(userAssetsInfo.price);
userAssetsInfo.borrowAssetSum = userAssetsInfo.borrowAssetSum.add(userAssetsInfo.borrowAsset);
}
}
}
}
if (userAssetsInfo.depositAssetBorrowLimitSum > userAssetsInfo.borrowAssetSum)
{
/* Set the amount that the user can borrow from the borrow limit and previous borrows. */
userAssetsInfo.userBorrowableAsset = userAssetsInfo.depositAssetBorrowLimitSum.sub(userAssetsInfo.borrowAssetSum);
/* Set the allowed amount that the user can withdraw based on the user borrow */
userAssetsInfo.withdrawableAsset = userAssetsInfo.depositAssetBorrowLimitSum.sub(userAssetsInfo.borrowAssetSum).unifiedDiv(userAssetsInfo.callerBorrowLimit);
}
/* Return the calculated parameters */
return (userAssetsInfo.userBorrowableAsset.unifiedDiv(userAssetsInfo.callerPrice), userAssetsInfo.withdrawableAsset.unifiedDiv(userAssetsInfo.callerPrice), userAssetsInfo.marginCallLimitSum, userAssetsInfo.depositAssetSum, userAssetsInfo.borrowAssetSum, userAssetsInfo.callerPrice);
}
/**
* @dev Reward the user (msg.sender) with the reward token after calculating interest.
* @return true (TODO: validate results)
*/
function interestUpdateReward() external override returns (bool)
{
uint256 thisBlock = block.number;
uint256 interestRewardUpdated = dataStorageInstance.getInterestRewardUpdated();
uint256 delta = thisBlock - interestRewardUpdated;
if (delta == 0)
{
return false;
}
dataStorageInstance.setInterestRewardUpdated(thisBlock);
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = tokenHandler.handlerProxy(abi.encodeWithSignature("checkFirstAction()"));
}
uint256 globalRewardPerBlock = dataStorageInstance.getInterestUpdateRewardPerblock();
uint256 rewardAmount = delta.mul(globalRewardPerBlock);
/* transfer reward tokens */
return _rewardTransfer(msg.sender, rewardAmount);
}
/**
* @dev (Update operation) update the rewards parameters.
* @param userAddr The address of operator
* @return Whether or not the operation succeed
*/
function updateRewardParams(address payable userAddr) external override returns (bool)
{
if (_determineRewardParams(userAddr))
{
return _calcRewardParams(userAddr);
}
return false;
}
/**
* @dev Claim all rewards for the user
* @param userAddr The user address
* @return true (TODO: validate results)
*/
function rewardClaimAll(address payable userAddr) external override returns (bool)
{
uint256 handlerID;
uint256 claimAmountSum;
bytes memory data;
for (handlerID; handlerID < tokenHandlerLength; handlerID++)
{
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));
(, data) = tokenHandler.siProxy(abi.encodeWithSignature(updateRewardLane, userAddr));
/* Claim reward for a token handler */
(, data) = tokenHandler.siProxy(abi.encodeWithSignature("claimRewardAmountUser(address)", userAddr));
claimAmountSum = claimAmountSum.add(abi.decode(data, (uint256)));
}
return _rewardTransfer(userAddr, claimAmountSum);
}
/**
* @dev Transfer reward tokens to owner (for administration)
* @param _amount The amount of the reward token
* @return true (TODO: validate results)
*/
function ownerRewardTransfer(uint256 _amount) onlyOwner external override returns (bool)
{
return _rewardTransfer(address(uint160(owner)), _amount);
}
/**
* @dev Transfer reward tokens to a user
* @param userAddr The address of recipient
* @param _amount The amount of the reward token
* @return true (TODO: validate results)
*/
function _rewardTransfer(address payable userAddr, uint256 _amount) internal returns (bool)
{
uint256 beforeBalance = rewardErc20Instance.balanceOf(userAddr);
rewardErc20Instance.transfer(userAddr, _amount);
uint256 afterBalance = rewardErc20Instance.balanceOf(userAddr);
require(_amount == afterBalance.sub(beforeBalance), REWARD_TRANSFER);
return true;
}
/**
* @dev (Update operation) update the rewards parameters (by using alpha- and
beta-score).
* @param userAddr The address of the operator
* @return Whether or not this process succeed
*/
function _determineRewardParams(address payable userAddr) internal returns (bool)
{
uint256 thisBlockNum = block.number;
managerDataStorageInterface _dataStorageInstance = dataStorageInstance;
/* The inactive period (delta) since the last action happens */
uint256 delta = thisBlockNum - _dataStorageInstance.getRewardParamUpdated();
_dataStorageInstance.setRewardParamUpdated(thisBlockNum);
if (delta == 0)
{
return false;
}
/* Rewards assigned for a block */
uint256 globalRewardPerBlock = _dataStorageInstance.getGlobalRewardPerBlock();
/* Rewards decrement for a block. (Rewards per block monotonically decreases) */
uint256 globalRewardDecrement = _dataStorageInstance.getGlobalRewardDecrement();
/* Total amount of rewards */
uint256 globalRewardTotalAmount = _dataStorageInstance.getGlobalRewardTotalAmount();
/* Remaining periods for reward distribution */
uint256 remainingPeriod = globalRewardPerBlock.unifiedDiv(globalRewardDecrement);
if (remainingPeriod >= delta.mul(SafeMath.unifiedPoint))
{
remainingPeriod = remainingPeriod.sub(delta.mul(SafeMath.unifiedPoint));
}
else
{
return _epilogueOfDetermineRewardParams(_dataStorageInstance, userAddr, delta, 0, globalRewardDecrement, 0);
}
if (globalRewardTotalAmount >= globalRewardPerBlock.mul(delta))
{
globalRewardTotalAmount = globalRewardTotalAmount - globalRewardPerBlock.mul(delta);
}
else
{
return _epilogueOfDetermineRewardParams(_dataStorageInstance, userAddr, delta, 0, globalRewardDecrement, 0);
}
globalRewardPerBlock = globalRewardTotalAmount.mul(2).unifiedDiv(remainingPeriod.add(SafeMath.unifiedPoint));
/* To incentivze the update operation, the operator get paid with the
reward token */
return _epilogueOfDetermineRewardParams(_dataStorageInstance, userAddr, delta, globalRewardPerBlock, globalRewardDecrement, globalRewardTotalAmount);
}
/**
* @dev Epilogue of _determineRewardParams for code-size savings
* @param _dataStorageInstance interface of Manager Data Storage
* @param userAddr User Address for Reward token transfer
* @param _delta The inactive period (delta) since the last action happens
* @param _globalRewardPerBlock Reward per block
* @param _globalRewardDecrement Rewards decrement for a block
* @param _globalRewardTotalAmount Total amount of rewards
* @return true (TODO: validate results)
*/
function _epilogueOfDetermineRewardParams(
managerDataStorageInterface _dataStorageInstance,
address payable userAddr,
uint256 _delta,
uint256 _globalRewardPerBlock,
uint256 _globalRewardDecrement,
uint256 _globalRewardTotalAmount
) internal returns (bool) {
_updateDeterminedRewardModelParam(_globalRewardPerBlock, _globalRewardDecrement, _globalRewardTotalAmount);
uint256 rewardAmount = _delta.mul(_dataStorageInstance.getRewardParamUpdateRewardPerBlock());
/* To incentivze the update operation, the operator get paid with the
reward token */
_rewardTransfer(userAddr, rewardAmount);
return true;
}
/**
* @dev Set the reward model parameters
* @param _rewardPerBlock Reward per block
* @param _dcrement Rewards decrement for a block
* @param _total Total amount of rewards
* @return true (TODO: validate results)
*/
function _updateDeterminedRewardModelParam(uint256 _rewardPerBlock, uint256 _dcrement, uint256 _total) internal returns (bool)
{
dataStorageInstance.setGlobalRewardPerBlock(_rewardPerBlock);
dataStorageInstance.setGlobalRewardDecrement(_dcrement);
dataStorageInstance.setGlobalRewardTotalAmount(_total);
return true;
}
/**
* @dev Update rewards paramters of token handlers.
* @param userAddr The address of operator
* @return true (TODO: validate results)
*/
function _calcRewardParams(address payable userAddr) internal returns (bool)
{
uint256 handlerLength = tokenHandlerLength;
bytes memory data;
uint256[] memory handlerAlphaRateBaseAsset = new uint256[](handlerLength);
uint256 handlerID;
uint256 alphaRateBaseGlobalAssetSum;
for (handlerID; handlerID < handlerLength; handlerID++)
{
handlerAlphaRateBaseAsset[handlerID] = _getAlphaBaseAsset(handlerID);
alphaRateBaseGlobalAssetSum = alphaRateBaseGlobalAssetSum.add(handlerAlphaRateBaseAsset[handlerID]);
}
handlerID = 0;
for (handlerID; handlerID < handlerLength; handlerID++)
{
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));
(, data) = tokenHandler.siProxy(abi.encodeWithSignature(updateRewardLane, userAddr));
/* Update reward parameter for the token handler */
data = abi.encodeWithSignature("updateRewardPerBlockLogic(uint256)",
dataStorageInstance.getGlobalRewardPerBlock()
.unifiedMul(
handlerAlphaRateBaseAsset[handlerID]
.unifiedDiv(alphaRateBaseGlobalAssetSum)
)
);
(, data) = tokenHandler.siProxy(data);
}
return true;
}
/**
* @dev Calculate the alpha-score for the handler (in USD price)
* @param _handlerID The handler ID
* @return The alpha-score of the handler
*/
function _getAlphaBaseAsset(uint256 _handlerID) internal view returns (uint256)
{
bytes memory data;
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(_handlerID));
(, data) = tokenHandler.handlerViewProxy(abi.encodeWithSignature("getDepositTotalAmount()"));
uint256 _depositAmount = abi.decode(data, (uint256));
(, data) = tokenHandler.handlerViewProxy(abi.encodeWithSignature("getBorrowTotalAmount()"));
uint256 _borrowAmount = abi.decode(data, (uint256));
uint256 _alpha = dataStorageInstance.getAlphaRate();
uint256 _price = _getTokenHandlerPrice(_handlerID);
return _calcAlphaBaseAmount(_alpha, _depositAmount, _borrowAmount).unifiedMul(_price);
}
/**
* @dev Calculate the alpha-score for the handler (in token amount)
* @param _alpha The alpha parameter
* @param _depositAmount The total amount of deposit
* @param _borrowAmount The total amount of borrow
* @return The alpha-score of the handler (in token amount)
*/
function _calcAlphaBaseAmount(uint256 _alpha, uint256 _depositAmount, uint256 _borrowAmount) internal pure returns (uint256)
{
return _depositAmount.unifiedMul(_alpha).add(_borrowAmount.unifiedMul(SafeMath.unifiedPoint.sub(_alpha)));
}
/**
* @dev Get the token price of the handler
* @param handlerID The handler ID
* @return The token price of the handler
*/
function getTokenHandlerPrice(uint256 handlerID) external view override returns (uint256)
{
return _getTokenHandlerPrice(handlerID);
}
/**
* @dev Get the margin call limit of the handler (external)
* @param handlerID The handler ID
* @return The margin call limit
*/
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view override returns (uint256)
{
return _getTokenHandlerMarginCallLimit(handlerID);
}
/**
* @dev Get the margin call limit of the handler (internal)
* @param handlerID The handler ID
* @return The margin call limit
*/
function _getTokenHandlerMarginCallLimit(uint256 handlerID) internal view returns (uint256)
{
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = tokenHandler.handlerViewProxy(abi.encodeWithSignature("getTokenHandlerMarginCallLimit()"));
return abi.decode(data, (uint256));
}
/**
* @dev Get the borrow limit of the handler (external)
* @param handlerID The handler ID
* @return The borrow limit
*/
function getTokenHandlerBorrowLimit(uint256 handlerID) external view override returns (uint256)
{
return _getTokenHandlerBorrowLimit(handlerID);
}
/**
* @dev Get the borrow limit of the handler (internal)
* @param handlerID The handler ID
* @return The borrow limit
*/
function _getTokenHandlerBorrowLimit(uint256 handlerID) internal view returns (uint256)
{
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = tokenHandler.handlerViewProxy(abi.encodeWithSignature("getTokenHandlerBorrowLimit()"));
return abi.decode(data, (uint256));
}
/**
* @dev Get the handler status of whether the handler is supported or not.
* @param handlerID The handler ID
* @return Whether the handler is supported or not
*/
function getTokenHandlerSupport(uint256 handlerID) external view override returns (bool)
{
return dataStorageInstance.getTokenHandlerSupport(handlerID);
}
/**
* @dev Set the length of the handler list
* @param _tokenHandlerLength The length of the handler list
* @return true (TODO: validate results)
*/
function setTokenHandlersLength(uint256 _tokenHandlerLength) onlyOwner external override returns (bool)
{
tokenHandlerLength = _tokenHandlerLength;
return true;
}
/**
* @dev Get the length of the handler list
* @return the length of the handler list
*/
function getTokenHandlersLength() external view override returns (uint256)
{
return tokenHandlerLength;
}
/**
* @dev Get the handler ID at the index in the handler list
* @param index The index of the handler list (array)
* @return The handler ID
*/
function getTokenHandlerID(uint256 index) external view override returns (uint256)
{
return dataStorageInstance.getTokenHandlerID(index);
}
/**
* @dev Get the amount of token that the user can borrow more
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The amount of token that user can borrow more
*/
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view override returns (uint256)
{
uint256 depositCredit;
uint256 borrowCredit;
(depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr);
if (depositCredit == 0)
{
return 0;
}
if (depositCredit > borrowCredit)
{
return depositCredit.sub(borrowCredit).unifiedDiv(_getTokenHandlerPrice(handlerID));
}
else
{
return 0;
}
}
/**
* @dev Get the deposit and borrow amount of the user with interest added
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount of the user with interest
*/
/* about user market Information function*/
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view override returns (uint256, uint256)
{
return _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
}
/**
* @dev Get the depositTotalCredit and borrowTotalCredit
* @param userAddr The address of the user
* @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit)
* @return borrowTotalCredit The sum of borrow amount for all handlers
*/
function getUserTotalIntraCreditAsset(address payable userAddr) external view override returns (uint256, uint256)
{
return _getUserTotalIntraCreditAsset(userAddr);
}
/**
* @dev Get the borrow and margin call limits of the user for all handlers
* @param userAddr The address of the user
* @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers
* @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers
*/
function getUserLimitIntraAsset(address payable userAddr) external view override returns (uint256, uint256)
{
uint256 userTotalBorrowLimitAsset;
uint256 userTotalMarginCallLimitAsset;
(userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset) = _getUserLimitIntraAsset(userAddr);
return (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset);
}
/**
* @dev Get the maximum allowed amount to borrow of the user from the given handler
* @param userAddr The address of the user
* @param callerID The target handler to borrow
* @return extraCollateralAmount The maximum allowed amount to borrow from
the handler.
*/
function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view override returns (uint256)
{
uint256 userTotalBorrowAsset;
uint256 depositAssetBorrowLimitSum;
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
userTotalBorrowAsset = userTotalBorrowAsset.add(borrowHandlerAsset);
depositAssetBorrowLimitSum = depositAssetBorrowLimitSum
.add(
depositHandlerAsset
.unifiedMul( _getTokenHandlerBorrowLimit(handlerID) )
);
}
}
if (depositAssetBorrowLimitSum > userTotalBorrowAsset)
{
return depositAssetBorrowLimitSum
.sub(userTotalBorrowAsset)
.unifiedDiv( _getTokenHandlerBorrowLimit(callerID) )
.unifiedDiv( _getTokenHandlerPrice(callerID) );
}
return 0;
}
/**
* @dev Partial liquidation for a user
* @param delinquentBorrower The address of the liquidation target
* @param liquidateAmount The amount to liquidate
* @param liquidator The address of the liquidator (liquidation operator)
* @param liquidateHandlerID The hander ID of the liquidating asset
* @param rewardHandlerID The handler ID of the reward token for the liquidator
* @return (uint256, uint256, uint256)
*/
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external override returns (uint256, uint256, uint256)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liquidateHandlerID);
proxyContractInterface tokenHandler = proxyContractInterface(tokenHandlerAddr);
bytes memory data;
data = abi.encodeWithSignature("partialLiquidationUser(address,uint256,address,uint256)", delinquentBorrower, liquidateAmount, liquidator, rewardHandlerID);
(, data) = tokenHandler.handlerProxy(data);
return abi.decode(data, (uint256, uint256, uint256));
}
/**
* @dev Get the maximum liquidation reward by checking sufficient reward
amount for the liquidator.
* @param delinquentBorrower The address of the liquidation target
* @param liquidateHandlerID The hander ID of the liquidating asset
* @param liquidateAmount The amount to liquidate
* @param rewardHandlerID The handler ID of the reward token for the liquidator
* @param rewardRatio delinquentBorrowAsset / delinquentDepositAsset
* @return The maximum reward token amount for the liquidator
*/
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view override returns (uint256)
{
uint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID);
uint256 rewardPrice = _getTokenHandlerPrice(rewardHandlerID);
uint256 delinquentBorrowerRewardDeposit;
(delinquentBorrowerRewardDeposit, ) = _getHandlerAmount(delinquentBorrower, rewardHandlerID);
uint256 rewardAsset = delinquentBorrowerRewardDeposit.unifiedMul(rewardPrice).unifiedMul(rewardRatio);
if (liquidateAmount.unifiedMul(liquidatePrice) > rewardAsset)
{
return rewardAsset.unifiedDiv(liquidatePrice);
}
else
{
return liquidateAmount;
}
}
/**
* @dev Reward the liquidator
* @param delinquentBorrower The address of the liquidation target
* @param rewardAmount The amount of reward token
* @param liquidator The address of the liquidator (liquidation operator)
* @param handlerID The handler ID of the reward token for the liquidator
* @return The amount of reward token
*/
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external override returns (uint256)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
proxyContractInterface tokenHandler = proxyContractInterface(tokenHandlerAddr);
bytes memory data;
data = abi.encodeWithSignature("partialLiquidationUserReward(address,uint256,address)", delinquentBorrower, rewardAmount, liquidator);
(, data) = tokenHandler.handlerProxy(data);
return abi.decode(data, (uint256));
}
/**
* @dev Get the deposit and borrow amount of the user for the handler (internal)
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount
*/
function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)
{
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = tokenHandler.handlerViewProxy(abi.encodeWithSignature("getUserAmount(address)", userAddr));
return abi.decode(data, (uint256, uint256));
}
/**
* @dev Set the support stauts for the handler
* @param handlerID the handler ID
* @param support the support status (boolean)
* @return true (TODO: validate results)
*/
function setHandlerSupport(uint256 handlerID, bool support) onlyOwner public returns (bool)
{
require(!dataStorageInstance.getTokenHandlerExist(handlerID), UNSUPPORTED_TOKEN);
/* activate or inactivate anyway*/
dataStorageInstance.setTokenHandlerSupport(handlerID, support);
return true;
}
/**
* @dev Get owner's address of the manager contract
* @return The address of owner
*/
function getOwner() public view returns (address)
{
return owner;
}
/**
* @dev Register a handler
* @param handlerID The handler ID
* @param handlerAddr The handler address
* @return true (TODO: validate results)
*/
function _handlerRegister(uint256 handlerID, address handlerAddr) internal returns (bool)
{
dataStorageInstance.setTokenHandler(handlerID, handlerAddr);
tokenHandlerLength = tokenHandlerLength + 1;
return true;
}
/**
* @dev Get the deposit and borrow amount of the user with interest added
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount of the user with interest
*/
function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)
{
uint256 price = _getTokenHandlerPrice(handlerID);
proxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));
uint256 depositAmount;
uint256 borrowAmount;
bytes memory data;
(, data) = tokenHandler.handlerViewProxy(abi.encodeWithSignature("getUserAmountWithInterest(address)", userAddr));
(depositAmount, borrowAmount) = abi.decode(data, (uint256, uint256));
uint256 depositAsset = depositAmount.unifiedMul(price);
uint256 borrowAsset = borrowAmount.unifiedMul(price);
return (depositAsset, borrowAsset);
}
/**
* @dev Get the borrow and margin call limits of the user for all handlers (internal)
* @param userAddr The address of the user
* @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers
* @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers
*/
function _getUserLimitIntraAsset(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 userTotalBorrowLimitAsset;
uint256 userTotalMarginCallLimitAsset;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);
uint256 marginCallLimit = _getTokenHandlerMarginCallLimit(handlerID);
uint256 userBorrowLimitAsset = depositHandlerAsset.unifiedMul(borrowLimit);
uint256 userMarginCallLimitAsset = depositHandlerAsset.unifiedMul(marginCallLimit);
userTotalBorrowLimitAsset = userTotalBorrowLimitAsset.add(userBorrowLimitAsset);
userTotalMarginCallLimitAsset = userTotalMarginCallLimitAsset.add(userMarginCallLimitAsset);
}
else
{
continue;
}
}
return (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset);
}
/**
* @dev Get the depositTotalCredit and borrowTotalCredit
* @param userAddr The address of the user
* @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit)
* @return borrowTotalCredit The sum of borrow amount for all handlers
*/
function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalCredit;
uint256 borrowTotalCredit;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);
uint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit);
depositTotalCredit = depositTotalCredit.add(depositHandlerCredit);
borrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset);
}
else
{
continue;
}
}
return (depositTotalCredit, borrowTotalCredit);
}
/**
* @dev Get the token price for the handler
* @param handlerID The handler id
* @return The token price of the handler
*/
function _getTokenHandlerPrice(uint256 handlerID) internal view returns (uint256)
{
return (oracleProxy.getTokenPrice(handlerID));
}
/**
* @dev Get the address of reward token
* @return The address of reward token
*/
function getRewardErc20() public view returns (address)
{
return address(rewardErc20Instance);
}
/**
* @dev Get the reward parameters
* @return (uint256,uint256,uint256) rewardPerBlock, rewardDecrement, rewardTotalAmount
*/
function getGlobalRewardInfo() external view override returns (uint256, uint256, uint256)
{
managerDataStorageInterface _dataStorage = dataStorageInstance;
return (_dataStorage.getGlobalRewardPerBlock(), _dataStorage.getGlobalRewardDecrement(), _dataStorage.getGlobalRewardTotalAmount());
}
}
|
Reward the liquidator delinquentBorrower The address of the liquidation target rewardAmount The amount of reward token liquidator The address of the liquidator (liquidation operator) handlerID The handler ID of the reward token for the liquidator return The amount of reward token/
|
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external override returns (uint256)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
proxyContractInterface tokenHandler = proxyContractInterface(tokenHandlerAddr);
bytes memory data;
data = abi.encodeWithSignature("partialLiquidationUserReward(address,uint256,address)", delinquentBorrower, rewardAmount, liquidator);
(, data) = tokenHandler.handlerProxy(data);
return abi.decode(data, (uint256));
}
| 6,491,405 |
./partial_match/1/0x10c8324B20b7266c445944f043F53F6A77ea0BD4/sources/MEGAWAVE.sol
|
reduce spender's allowance to 0 then set desired value after to avoid race condition
|
function approve(address _spender, uint256 _amount) public returns(bool) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
| 3,721,813 |
./partial_match/80001/0x29f049fD25bFC402CDc0c7aa3f3Fa9724CE7FAEE/sources/FxChild.sol
|
IStateReceiver represents interface to receive state
|
interface IStateReceiver {
function onStateReceive(uint256 stateId, bytes calldata data) external;
}
| 8,796,857 |
pragma solidity ^0.5.17;
library Math {
function MAX540(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE579(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
library SafeMath {
function ADD537(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB533(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB533(a, b, "SafeMath: subtraction overflow");
}
function SUB533(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 MUL899(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 DIV732(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV732(a, b, "SafeMath: division by zero");
}
function DIV732(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 MOD804(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD804(a, b, "SafeMath: modulo by zero");
}
function MOD804(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
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 _MSGSENDER75() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA657() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED138(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER75();
emit OWNERSHIPTRANSFERRED138(address(0), _owner);
}
function OWNER313() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER471() { //inject NONSTANDARD NAMING
require(ISOWNER999(), "Ownable: caller is not the owner");
_;
}
function ISOWNER999() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER75() == _owner;
}
function RENOUNCEOWNERSHIP459() public ONLYOWNER471 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED138(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP87(address newOwner) public ONLYOWNER471 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP967(newOwner);
}
function _TRANSFEROWNERSHIP967(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED138(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
interface IERC20 {
function MINT669(address account, uint amount) external; //inject NONSTANDARD NAMING
function TOTALSUPPLY186() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF689(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER213(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE163(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE444(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM175(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER653(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL189(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
library Address {
function ISCONTRACT844(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE974(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE557(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER881(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.TRANSFER213.selector, to, value));
}
function SAFETRANSFERFROM203(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.TRANSFERFROM175.selector, from, to, value));
}
function SAFEAPPROVE790(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.ALLOWANCE163(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.APPROVE444.selector, spender, value));
}
function SAFEINCREASEALLOWANCE320(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE163(address(this), spender).ADD537(value);
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.APPROVE444.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE576(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE163(address(this), spender).SUB533(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.APPROVE444.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN468(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).ISCONTRACT844(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/IRewardDistributionRecipient.sol
pragma solidity ^0.5.0;
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution = 0x45a6b8BdfC1FAa745720165e0B172A3D6D4EC897;
function NOTIFYREWARDAMOUNT985() external; //inject NONSTANDARD NAMING
modifier ONLYREWARDDISTRIBUTION252() { //inject NONSTANDARD NAMING
require(_MSGSENDER75() == rewardDistribution, "Caller is not reward distribution");
_;
}
function SETREWARDDISTRIBUTION691(address _rewardDistribution) //inject NONSTANDARD NAMING
external
ONLYOWNER471
{
rewardDistribution = _rewardDistribution;
}
}
// File: contracts/CurveRewards.sol
pragma solidity ^0.5.0;
pragma solidity ^0.5.17;
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public vamp_lp = IERC20(0x7dd8f4ABF60b58CE989DB66aB1af1d11E893429D); //vamp_lp mainnet
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function TOTALSUPPLY186() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF689(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function STAKE760(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.ADD537(amount);
_balances[msg.sender] = _balances[msg.sender].ADD537(amount);
vamp_lp.SAFETRANSFERFROM203(msg.sender, address(this), amount);
}
function WITHDRAW940(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.SUB533(amount);
_balances[msg.sender] = _balances[msg.sender].SUB533(amount);
vamp_lp.SAFETRANSFER881(msg.sender, amount);
}
}
contract VMANAVAMPPool is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public vamp = IERC20(0xb2C822a1b923E06Dbd193d2cFc7ad15388EA09DD); //vmana
uint256 public DURATION = 7 days;
uint256 public initreward = 801419450000000000000000;
uint256 public starttime = 1603573200; //1 hour after vmana ends
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event REWARDADDED399(uint256 reward); //inject NONSTANDARD NAMING
event STAKED507(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAWN5(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event REWARDPAID848(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
modifier UPDATEREWARD996(address account) { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN216();
lastUpdateTime = LASTTIMEREWARDAPPLICABLE527();
if (account != address(0)) {
rewards[account] = EARNED802(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function LASTTIMEREWARDAPPLICABLE527() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN509(block.timestamp, periodFinish);
}
function REWARDPERTOKEN216() public view returns (uint256) { //inject NONSTANDARD NAMING
if (TOTALSUPPLY186() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.ADD537(
LASTTIMEREWARDAPPLICABLE527()
.SUB533(lastUpdateTime)
.MUL899(rewardRate)
.MUL899(1e18)
.DIV732(TOTALSUPPLY186())
);
}
function EARNED802(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return
BALANCEOF689(account)
.MUL899(REWARDPERTOKEN216().SUB533(userRewardPerTokenPaid[account]))
.DIV732(1e18)
.ADD537(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function STAKE760(uint256 amount) public UPDATEREWARD996(msg.sender) CHECKSTART317{ //inject NONSTANDARD NAMING
require(amount > 0, "Cannot stake 0");
super.STAKE760(amount);
emit STAKED507(msg.sender, amount);
}
function WITHDRAW940(uint256 amount) public UPDATEREWARD996(msg.sender) { //inject NONSTANDARD NAMING
require(amount > 0, "Cannot withdraw 0");
super.WITHDRAW940(amount);
emit WITHDRAWN5(msg.sender, amount);
}
function EXIT850() external { //inject NONSTANDARD NAMING
WITHDRAW940(BALANCEOF689(msg.sender));
GETREWARD327();
}
function GETREWARD327() public UPDATEREWARD996(msg.sender) { //inject NONSTANDARD NAMING
uint256 reward = EARNED802(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
vamp.SAFETRANSFER881(msg.sender, reward);
emit REWARDPAID848(msg.sender, reward);
}
}
function AFTEREND949() public ONLYREWARDDISTRIBUTION252 { //if any tokens left, transfer to contract owner for further distriubtion to community //inject NONSTANDARD NAMING
require(block.timestamp > periodFinish);
vamp.SAFETRANSFER881(msg.sender,vamp.BALANCEOF689(address(this)));
}
modifier CHECKSTART317(){ //inject NONSTANDARD NAMING
require(block.timestamp > starttime,"not start");
_;
}
function NOTIFYREWARDAMOUNT985() //inject NONSTANDARD NAMING
external
ONLYREWARDDISTRIBUTION252
UPDATEREWARD996(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = initreward.DIV732(DURATION);
} else {
uint256 remaining = periodFinish.SUB533(block.timestamp);
uint256 leftover = remaining.MUL899(rewardRate);
rewardRate = initreward.ADD537(leftover).DIV732(DURATION);
}
//vamp.mint(address(this),initreward);
lastUpdateTime = block.timestamp;
periodFinish = starttime.ADD537(DURATION);
emit REWARDADDED399(initreward);
}
}
|
inject NONSTANDARD NAMING
|
function WITHDRAW940(uint256 amount) public UPDATEREWARD996(msg.sender) {
| 6,417,111 |
pragma solidity ^0.5.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/BountyCreator.sol";
/** @title TestBountyCreator
@dev The contract testing the functionalities of the BountyCreator contract
@author Smit Rajput
*/
contract TestBountyCreator {
/** Storage */
BountyCreator creator;
/** @dev The test hook to create a BountyCreator before every test
*/
function beforeEach() public {
creator = new BountyCreator("Bob", 0x76E1D4aB082Cc05F2439F8918937F5B26cc3AEb7);
}
/** @dev To test the creation of a valid bounty by checking on the total number of bounties
*/
function testCreatingBounty() public {
creator.createBounty("some task", 5);
Assert.equal(creator.numberOfBounties(), 1, "It should create a bounty");
}
/** @dev To check the creation of 2 valid submissions for a bounty by checking
on the incrementation in submission IDs
@notice subID = 0, after 1st submission
subID = 1, after 2nd submission
*/
function testCreatingSubmssions() public {
uint subID;
creator.createBounty("some task", 5);
subID = creator.createSub(0, "first solution");
subID = creator.createSub(0, "second solution");
Assert.equal(subID, 1, "It should create 2 submissions");
}
/** @dev To check if the 1st 3 details of a bounty are properly retrievable
*/
function testSomeBountyDetails() public {
uint bountyID = creator.createBounty("some task", 5);
(string memory task, uint reward, uint numberOfSubmissions,,,) = creator.getBountyDetails(bountyID);
Assert.equal(task, "some task", "It should return the bounty description");
Assert.equal(reward, 0, "It should return the bounty reward");
Assert.equal(numberOfSubmissions, 0, "It should return the number of submissions of a bounty");
}
/** @dev To check if the details of a submission are retrievable
*/
function testGettingSubmissionDetails() public {
uint bountyID = creator.createBounty("some task", 5);
uint subID = creator.createSub(0, "a solution");
(string memory solution,,) = creator.getSubDetails(bountyID, subID);
Assert.equal(solution, "a solution", "It should return all the submssion details");
}
/** @dev To check if the start and the expiry times of a bounty are retrievable and valid
*/
function testNewBountyExpiryTime() public {
uint bountyID = creator.createBounty("some task", 5);
(,,,,uint startTime, uint expiryTime) = creator.getBountyDetails(bountyID);
Assert.isAbove(expiryTime-startTime, 0, "It should return a strictly positive bounty expiry time");
}
}
|
To check if the 1st 3 details of a bounty are properly retrievable/
|
function testSomeBountyDetails() public {
uint bountyID = creator.createBounty("some task", 5);
(string memory task, uint reward, uint numberOfSubmissions,,,) = creator.getBountyDetails(bountyID);
Assert.equal(task, "some task", "It should return the bounty description");
Assert.equal(reward, 0, "It should return the bounty reward");
Assert.equal(numberOfSubmissions, 0, "It should return the number of submissions of a bounty");
}
| 14,050,710 |
pragma solidity ^0.4.24;
/*
* gibmireinbier
* 0xA4a799086aE18D7db6C4b57f496B081b44888888
* [email protected]
*/
library Helper {
using SafeMath for uint256;
uint256 constant public ZOOM = 1000;
uint256 constant public SDIVIDER = 3450000;
uint256 constant public PDIVIDER = 3450000;
uint256 constant public RDIVIDER = 1580000;
// Starting LS price (SLP)
uint256 constant public SLP = 0.002 ether;
// Starting Added Time (SAT)
uint256 constant public SAT = 30; // seconds
// Price normalization (PN)
uint256 constant public PN = 777;
// EarlyIncome base
uint256 constant public PBASE = 13;
uint256 constant public PMULTI = 26;
uint256 constant public LBase = 15;
uint256 constant public ONE_HOUR = 3600;
uint256 constant public ONE_DAY = 24 * ONE_HOUR;
//uint256 constant public TIMEOUT0 = 3 * ONE_HOUR;
uint256 constant public TIMEOUT1 = 12 * ONE_HOUR;
function bytes32ToString (bytes32 data)
public
pure
returns (string)
{
bytes memory bytesString = new bytes(32);
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
}
}
return string(bytesString);
}
function uintToBytes32(uint256 n)
public
pure
returns (bytes32)
{
return bytes32(n);
}
function bytes32ToUint(bytes32 n)
public
pure
returns (uint256)
{
return uint256(n);
}
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 stringToUint(string memory source)
public
pure
returns (uint256)
{
return bytes32ToUint(stringToBytes32(source));
}
function uintToString(uint256 _uint)
public
pure
returns (string)
{
return bytes32ToString(uintToBytes32(_uint));
}
/*
function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) {
bytes memory a = new bytes(end-begin+1);
for(uint i = 0; i <= end - begin; i++){
a[i] = bytes(text)[i + begin - 1];
}
return string(a);
}
*/
function validUsername(string _username)
public
pure
returns(bool)
{
uint256 len = bytes(_username).length;
// Im Raum [4, 18]
if ((len < 4) || (len > 18)) return false;
// Letzte Char != ' '
if (bytes(_username)[len-1] == 32) return false;
// Erste Char != '0'
return uint256(bytes(_username)[0]) != 48;
}
// Lottery Helper
// Seconds added per LT = SAT - ((Current no. of LT + 1) / SDIVIDER)^6
function getAddedTime(uint256 _rTicketSum, uint256 _tAmount)
public
pure
returns (uint256)
{
//Luppe = 10000 = 10^4
uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER;
uint256 expo = base;
expo = expo.mul(expo).mul(expo); // ^3
expo = expo.mul(expo); // ^6
// div 10000^6
expo = expo / (10**24);
if (expo > SAT) return 0;
return (SAT - expo).mul(_tAmount);
}
function getNewEndTime(uint256 toAddTime, uint256 slideEndTime, uint256 fixedEndTime)
public
view
returns(uint256)
{
uint256 _slideEndTime = (slideEndTime).add(toAddTime);
uint256 timeout = _slideEndTime.sub(block.timestamp);
// timeout capped at TIMEOUT1
if (timeout > TIMEOUT1) timeout = TIMEOUT1;
_slideEndTime = (block.timestamp).add(timeout);
// Capped at fixedEndTime
if (_slideEndTime > fixedEndTime) return fixedEndTime;
return _slideEndTime;
}
// get random in range [1, _range] with _seed
function getRandom(uint256 _seed, uint256 _range)
public
pure
returns(uint256)
{
if (_range == 0) return _seed;
return (_seed % _range) + 1;
}
function getEarlyIncomeMul(uint256 _ticketSum)
public
pure
returns(uint256)
{
// Early-Multiplier = 1 + PBASE / (1 + PMULTI * ((Current No. of LT)/RDIVIDER)^6)
uint256 base = _ticketSum * ZOOM / RDIVIDER;
uint256 expo = base.mul(base).mul(base); //^3
expo = expo.mul(expo) / (ZOOM**6); //^6
return (1 + PBASE / (1 + expo.mul(PMULTI)));
}
// get reveiced Tickets, based on current round ticketSum
function getTAmount(uint256 _ethAmount, uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 _tPrice = getTPrice(_ticketSum);
return _ethAmount.div(_tPrice);
}
// Lotto-Multiplier = 1 + LBase * (Current No. of Tickets / PDivider)^6
function getTMul(uint256 _ticketSum) // Unit Wei
public
pure
returns(uint256)
{
uint256 base = _ticketSum * ZOOM / PDIVIDER;
uint256 expo = base.mul(base).mul(base);
expo = expo.mul(expo); // ^6
return 1 + expo.mul(LBase) / (10**18);
}
// get ticket price, based on current round ticketSum
//unit in ETH, no need / zoom^6
function getTPrice(uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER;
uint256 expo = base;
expo = expo.mul(expo).mul(expo); // ^3
expo = expo.mul(expo); // ^6
uint256 tPrice = SLP + expo / PN;
return tPrice;
}
// get weight of slot, chance to win grandPot
function getSlotWeight(uint256 _ethAmount, uint256 _ticketSum)
public
pure
returns(uint256)
{
uint256 _tAmount = getTAmount(_ethAmount, _ticketSum);
uint256 _tMul = getTMul(_ticketSum);
return (_tAmount).mul(_tMul);
}
// used to draw grandpot results
// weightRange = roundWeight * grandpot / (grandpot - initGrandPot)
// grandPot = initGrandPot + round investedSum(for grandPot)
function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight)
public
pure
returns(uint256)
{
//calculate round grandPot-investedSum
uint256 grandPotInvest = grandPot - initGrandPot;
if (grandPotInvest == 0) return 8;
uint256 zoomMul = grandPot * ZOOM / grandPotInvest;
uint256 weightRange = zoomMul * curRWeight / ZOOM;
if (weightRange < curRWeight) weightRange = curRWeight;
return weightRange;
}
}
interface F2mInterface {
function joinNetwork(address[6] _contract) public;
// one time called
function disableRound0() public;
function activeBuy() public;
// Dividends from all sources (DApps, Donate ...)
function pushDividends() public payable;
/**
* Converts all of caller's dividends to tokens.
*/
//function reinvest() public;
//function buy() public payable;
function buyFor(address _buyer) public payable;
function sell(uint256 _tokenAmount) public;
function exit() public;
function devTeamWithdraw() public returns(uint256);
function withdrawFor(address sender) public returns(uint256);
function transfer(address _to, uint256 _tokenAmount) public returns(bool);
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
function setAutoBuy() public;
/*==========================================
= public FUNCTIONS =
==========================================*/
// function totalEthBalance() public view returns(uint256);
function ethBalance(address _address) public view returns(uint256);
function myBalance() public view returns(uint256);
function myEthBalance() public view returns(uint256);
function swapToken() public;
function setNewToken(address _newTokenAddress) public;
}
interface BankInterface {
function joinNetwork(address[6] _contract) public;
// Core functions
function pushToBank(address _player) public payable;
}
interface DevTeamInterface {
function setF2mAddress(address _address) public;
function setLotteryAddress(address _address) public;
function setCitizenAddress(address _address) public;
function setBankAddress(address _address) public;
function setRewardAddress(address _address) public;
function setWhitelistAddress(address _address) public;
function setupNetwork() public;
}
interface LotteryInterface {
function joinNetwork(address[6] _contract) public;
// call one time
function activeFirstRound() public;
// Core Functions
function pushToPot() public payable;
function finalizeable() public view returns(bool);
// bounty
function finalize() public;
function buy(string _sSalt) public payable;
function buyFor(string _sSalt, address _sender) public payable;
//function withdraw() public;
function withdrawFor(address _sender) public returns(uint256);
function getRewardBalance(address _buyer) public view returns(uint256);
function getTotalPot() public view returns(uint256);
// EarlyIncome
function getEarlyIncomeByAddress(address _buyer) public view returns(uint256);
// included claimed amount
// function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256);
function getCurEarlyIncomeByAddress(address _buyer) public view returns(uint256);
// function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256);
function getCurRoundId() public view returns(uint256);
// set endRound, prepare to upgrade new version
function setLastRound(uint256 _lastRoundId) public;
function getPInvestedSumByRound(uint256 _rId, address _buyer) public view returns(uint256);
function cashoutable(address _address) public view returns(bool);
function isLastRound() public view returns(bool);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts 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));
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Adds two signed integers, reverts 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));
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Citizen {
using SafeMath for uint256;
event Register(address indexed _member, address indexed _ref);
modifier withdrawRight(){
require((msg.sender == address(bankContract)), "Bank only");
_;
}
modifier onlyAdmin() {
require(msg.sender == devTeam, "admin required");
_;
}
modifier notRegistered(){
require(!isCitizen[msg.sender], "already exist");
_;
}
modifier registered(){
require(isCitizen[msg.sender], "must be a citizen");
_;
}
struct Profile{
uint256 id;
uint256 username;
uint256 refWallet;
address ref;
address[] refTo;
uint256 totalChild;
uint256 donated;
uint256 treeLevel;
// logs
uint256 totalSale;
uint256 allRoundRefIncome;
mapping(uint256 => uint256) roundRefIncome;
mapping(uint256 => uint256) roundRefWallet;
}
//bool public oneWayTicket = true;
mapping (address => Profile) public citizen;
mapping (address => bool) public isCitizen;
mapping (uint256 => address) public idAddress;
mapping (uint256 => address) public usernameAddress;
mapping (uint256 => address[]) levelCitizen;
BankInterface bankContract;
LotteryInterface lotteryContract;
F2mInterface f2mContract;
address devTeam;
uint256 citizenNr;
uint256 lastLevel;
// logs
mapping(uint256 => uint256) public totalRefByRound;
uint256 public totalRefAllround;
constructor (address _devTeam)
public
{
DevTeamInterface(_devTeam).setCitizenAddress(address(this));
devTeam = _devTeam;
// first citizen is the development team
citizenNr = 1;
idAddress[1] = devTeam;
isCitizen[devTeam] = true;
//root => self ref
citizen[devTeam].ref = devTeam;
// username rules bypass
uint256 _username = Helper.stringToUint("f2m");
citizen[devTeam].username = _username;
usernameAddress[_username] = devTeam;
citizen[devTeam].id = 1;
citizen[devTeam].treeLevel = 1;
levelCitizen[1].push(devTeam);
lastLevel = 1;
}
// _contract = [f2mAddress, bankAddress, citizenAddress, lotteryAddress, rewardAddress, whitelistAddress];
function joinNetwork(address[6] _contract)
public
{
require(address(lotteryContract) == 0,"already setup");
f2mContract = F2mInterface(_contract[0]);
bankContract = BankInterface(_contract[1]);
lotteryContract = LotteryInterface(_contract[3]);
}
/*---------- WRITE FUNCTIONS ----------*/
function updateTotalChild(address _address)
private
{
address _member = _address;
while(_member != devTeam) {
_member = getRef(_member);
citizen[_member].totalChild ++;
}
}
function register(string _sUsername, address _ref)
public
notRegistered()
{
require(Helper.validUsername(_sUsername), "invalid username");
address sender = msg.sender;
uint256 _username = Helper.stringToUint(_sUsername);
require(usernameAddress[_username] == 0x0, "username already exist");
usernameAddress[_username] = sender;
//ref must be a citizen, else ref = devTeam
address validRef = isCitizen[_ref] ? _ref : devTeam;
//Welcome new Citizen
isCitizen[sender] = true;
citizen[sender].username = _username;
citizen[sender].ref = validRef;
citizenNr++;
idAddress[citizenNr] = sender;
citizen[sender].id = citizenNr;
uint256 refLevel = citizen[validRef].treeLevel;
if (refLevel == lastLevel) lastLevel++;
citizen[sender].treeLevel = refLevel + 1;
levelCitizen[refLevel + 1].push(sender);
//add child
citizen[validRef].refTo.push(sender);
updateTotalChild(sender);
emit Register(sender, validRef);
}
function updateUsername(string _sNewUsername)
public
registered()
{
require(Helper.validUsername(_sNewUsername), "invalid username");
address sender = msg.sender;
uint256 _newUsername = Helper.stringToUint(_sNewUsername);
require(usernameAddress[_newUsername] == 0x0, "username already exist");
uint256 _oldUsername = citizen[sender].username;
citizen[sender].username = _newUsername;
usernameAddress[_oldUsername] = 0x0;
usernameAddress[_newUsername] = sender;
}
//Sources: Token contract, DApps
function pushRefIncome(address _sender)
public
payable
{
uint256 curRoundId = lotteryContract.getCurRoundId();
uint256 _amount = msg.value;
address sender = _sender;
address ref = getRef(sender);
// logs
citizen[sender].totalSale += _amount;
totalRefAllround += _amount;
totalRefByRound[curRoundId] += _amount;
// push to root
// lower level cost less gas
while (sender != devTeam) {
_amount = _amount / 2;
citizen[ref].refWallet = _amount.add(citizen[ref].refWallet);
citizen[ref].roundRefIncome[curRoundId] += _amount;
citizen[ref].allRoundRefIncome += _amount;
sender = ref;
ref = getRef(sender);
}
citizen[sender].refWallet = _amount.add(citizen[ref].refWallet);
// devTeam Logs
citizen[sender].roundRefIncome[curRoundId] += _amount;
citizen[sender].allRoundRefIncome += _amount;
}
function withdrawFor(address sender)
public
withdrawRight()
returns(uint256)
{
uint256 amount = citizen[sender].refWallet;
if (amount == 0) return 0;
citizen[sender].refWallet = 0;
bankContract.pushToBank.value(amount)(sender);
return amount;
}
function devTeamWithdraw()
public
onlyAdmin()
{
uint256 _amount = citizen[devTeam].refWallet;
if (_amount == 0) return;
devTeam.transfer(_amount);
citizen[devTeam].refWallet = 0;
}
function devTeamReinvest()
public
returns(uint256)
{
address sender = msg.sender;
require(sender == address(f2mContract), "only f2m contract");
uint256 _amount = citizen[devTeam].refWallet;
citizen[devTeam].refWallet = 0;
address(f2mContract).transfer(_amount);
return _amount;
}
/*---------- READ FUNCTIONS ----------*/
function getTotalChild(address _address)
public
view
returns(uint256)
{
return citizen[_address].totalChild;
}
function getAllRoundRefIncome(address _address)
public
view
returns(uint256)
{
return citizen[_address].allRoundRefIncome;
}
function getRoundRefIncome(address _address, uint256 _rId)
public
view
returns(uint256)
{
return citizen[_address].roundRefIncome[_rId];
}
function getRefWallet(address _address)
public
view
returns(uint256)
{
return citizen[_address].refWallet;
}
function getAddressById(uint256 _id)
public
view
returns (address)
{
return idAddress[_id];
}
function getAddressByUserName(string _username)
public
view
returns (address)
{
return usernameAddress[Helper.stringToUint(_username)];
}
function exist(string _username)
public
view
returns (bool)
{
return usernameAddress[Helper.stringToUint(_username)] != 0x0;
}
function getId(address _address)
public
view
returns (uint256)
{
return citizen[_address].id;
}
function getUsername(address _address)
public
view
returns (string)
{
if (!isCitizen[_address]) return "";
return Helper.uintToString(citizen[_address].username);
}
function getUintUsername(address _address)
public
view
returns (uint256)
{
return citizen[_address].username;
}
function getRef(address _address)
public
view
returns (address)
{
return citizen[_address].ref == 0x0 ? devTeam : citizen[_address].ref;
}
function getRefTo(address _address)
public
view
returns (address[])
{
return citizen[_address].refTo;
}
function getRefToById(address _address, uint256 _id)
public
view
returns (address, string, uint256, uint256, uint256, uint256)
{
address _refTo = citizen[_address].refTo[_id];
return (
_refTo,
Helper.uintToString(citizen[_refTo].username),
citizen[_refTo].treeLevel,
citizen[_refTo].refTo.length,
citizen[_refTo].refWallet,
citizen[_refTo].totalSale
);
}
function getRefToLength(address _address)
public
view
returns (uint256)
{
return citizen[_address].refTo.length;
}
function getLevelCitizenLength(uint256 _level)
public
view
returns (uint256)
{
return levelCitizen[_level].length;
}
function getLevelCitizenById(uint256 _level, uint256 _id)
public
view
returns (address)
{
return levelCitizen[_level][_id];
}
function getCitizenLevel(address _address)
public
view
returns (uint256)
{
return citizen[_address].treeLevel;
}
function getLastLevel()
public
view
returns(uint256)
{
return lastLevel;
}
}
|
ref must be a citizen, else ref = devTeamWelcome new Citizenadd child
|
function register(string _sUsername, address _ref)
public
notRegistered()
{
require(Helper.validUsername(_sUsername), "invalid username");
address sender = msg.sender;
uint256 _username = Helper.stringToUint(_sUsername);
require(usernameAddress[_username] == 0x0, "username already exist");
usernameAddress[_username] = sender;
address validRef = isCitizen[_ref] ? _ref : devTeam;
isCitizen[sender] = true;
citizen[sender].username = _username;
citizen[sender].ref = validRef;
citizenNr++;
idAddress[citizenNr] = sender;
citizen[sender].id = citizenNr;
uint256 refLevel = citizen[validRef].treeLevel;
if (refLevel == lastLevel) lastLevel++;
citizen[sender].treeLevel = refLevel + 1;
levelCitizen[refLevel + 1].push(sender);
citizen[validRef].refTo.push(sender);
updateTotalChild(sender);
emit Register(sender, validRef);
}
| 12,686,268 |
./partial_match/42/0x0C7e9B502Ce3239c6A5dcaF9392D9bE9215d9AdC/sources/ChainLog.sol
|
Returns the address for a particular key _key a bytes32 key (ex. MCD_VAT) return addr the contract address associated with the key
|
function getAddress(bytes32 _key) public view returns (address addr) {
addr = location[_key].addr;
require(addr != address(0), "dss-chain-log/invalid-key");
}
| 3,357,817 |
./full_match/1/0x181cfD48e5d22233e8B5C5dd3908123A2d9Ef733/sources/browser/YFMSVaults.sol
|
returns all users currently staking in this vault.
|
function getStakers() public view returns (address[] memory) {
return stakers;
}
| 4,826,549 |
./full_match/84531/0x23635e486de7B688b07F4CEe917D447dAf8acE3E/sources/contracts/ERC20MintablePauseableUpgradeable.sol
|
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
|
{
address public implementation;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
mapping(address => bool) private blackList;
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
function initialize(
string memory name,
string memory symbol,
uint256 initialSupply,
address owner
pragma solidity ^0.8.0;
) public initializer {
__ERC20_init(name, symbol);
__EIP712_init("PermitToken", "1.0");
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_mint(owner, initialSupply);
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "forbidden");
_;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20Upgradeable, ERC20PausableUpgradeable) {
require(!blackList[from], "forbidden");
super._beforeTokenTransfer(from, to, amount);
}
function setBlackList(address account) public onlyAdmin {
blackList[account] = !blackList[account];
}
function getBlackList(address account)
public
view
onlyAdmin
returns (bool)
{
return blackList[account];
}
function mint(address to, uint256 amount) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have minter role to mint"
);
_mint(to, amount);
}
function pause() public onlyAdmin {
_pause();
}
function unpause() public onlyAdmin {
_unpause();
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
bytes memory signature
) public {
bytes32 structHash = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, signature);
require(owner == signer, "Permit: invalid signature");
_approve(owner, spender, value);
}
}
| 14,302,592 |
./full_match/80001/0x0392F6416DCA6305A7aB44A7652fE12c6367322c/sources/marketplaceupdated.sol
|
Places a bid for a published NFT and checks for the asset fingerprint _nftAddress - Address of the NFT registry _assetId - ID of the published NFT _expiresAt - Bid expiration time/
|
function safePlaceBid(address _nftAddress, uint256 _assetId, uint256 _expiresAt, uint256 _priceInWei)
public payable whenNotPaused {
Order memory order = _getValidOrder(_nftAddress, _assetId);
uint256 price;
if(order.currency == 0x0000000000000000000000000000000000000000) {
price = msg.value;
}
else {
price = _priceInWei;
}
_createBid(_nftAddress, _assetId, price, _expiresAt);
}
| 5,579,275 |
./full_match/80001/0x809420EEE145CE61be213Bd4AE40885cE8b11E8e/sources/contracts/testnetGenerateV2.sol
|
Retrieves an available token at the specified index. indexToUse The index to use. updatedNumAvailableTokens The updated number of available tokens./
|
function getAvailableTokenAtIndex(
uint256 indexToUse,
uint256 updatedNumAvailableTokens
) internal returns (uint256 result) {
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 lastIndex = updatedNumAvailableTokens - 1;
uint256 lastValInArray = _availableTokens[lastIndex];
result = valAtIndex == 0 ? indexToUse : valAtIndex;
if (indexToUse != lastIndex) {
_availableTokens[indexToUse] = lastValInArray == 0
? lastIndex
: lastValInArray;
}
if (lastValInArray != 0) {
delete _availableTokens[lastIndex];
}
}
| 840,007 |
./full_match/1/0x1a6aa939A1682Cdffa08a35c22795d933AF9A116/sources/EthernaalFlaNft.sol
|
This function is used to check if it is the first sale of a token on the Ethernaal marketplace./
|
function isTokenFirstSale(uint tokenId) external view returns(bool){
return tokenFirstSale[tokenId];
}
| 5,000,937 |
./full_match/1/0x2DE9441C3e22725474146450FC3467A2c778040F/sources/pickle.sol
|
Recalls all the deposited funds from a vault to this contract. _vaultId the identifier of the recall funds from. return the amount of funds that were recalled from the vault to this contract and the decreased vault value. Please note this strategy will have 1.5% + 3crv/dai slippage lost
|
function recallAll(uint256 _vaultId) external nonReentrant expectInitialized returns (uint256, uint256) {
VaultV2.Data storage _vault = _vaults.get(_vaultId);
return _recallFunds(_vaultId, _vault.totalDeposited * (1000-slippage) / 1000);
}
| 3,122,678 |
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "./base/ModuleManager.sol";
import "./base/OwnerManager.sol";
import "./base/FallbackManager.sol";
import "./base/GuardManager.sol";
import "./common/EtherPaymentFallback.sol";
import "./common/Singleton.sol";
import "./common/SignatureDecoder.sol";
import "./common/SecuredTokenTransfer.sol";
import "./common/StorageAccessible.sol";
import "./interfaces/ISignatureValidator.sol";
import "./external/GnosisSafeMath.sol";
/// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract GnosisSafe is
EtherPaymentFallback,
Singleton,
ModuleManager,
OwnerManager,
SignatureDecoder,
SecuredTokenTransfer,
ISignatureValidatorConstants,
FallbackManager,
StorageAccessible,
GuardManager
{
using GnosisSafeMath for uint256;
string public constant VERSION = "1.3.0";
// keccak256(
// "EIP712Domain(uint256 chainId,address verifyingContract)"
// );
bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
// keccak256(
// "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
// );
bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
event SignMsg(bytes32 indexed msgHash);
event ExecutionFailure(bytes32 txHash, uint256 payment);
event ExecutionSuccess(bytes32 txHash, uint256 payment);
uint256 public nonce;
bytes32 private _deprecatedDomainSeparator;
// Mapping to keep track of all message hashes that have been approved by ALL REQUIRED owners
mapping(bytes32 => uint256) public signedMessages;
// Mapping to keep track of all hashes (message or transaction) that have been approved by ANY owners
mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
// This constructor ensures that this contract can only be used as a master copy for Proxy contracts
constructor() {
// By setting the threshold it is not possible to call setup anymore,
// so we create a Safe with 0 owners and threshold 1.
// This is an unusable Safe, perfect for the singleton
threshold = 1;
}
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
/// @param to Contract address for optional delegate call.
/// @param data Data payload for optional delegate call.
/// @param fallbackHandler Handler for fallback calls to this contract
/// @param paymentToken Token that should be used for the payment (0 is ETH)
/// @param payment Value that should be paid
/// @param paymentReceiver Address that should receive the payment (or 0 if tx.origin)
function setup(
address[] calldata _owners,
uint256 _threshold,
address to,
bytes calldata data,
address fallbackHandler,
address paymentToken,
uint256 payment,
address payable paymentReceiver
) external {
// setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
setupOwners(_owners, _threshold);
if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
// As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
setupModules(to, data);
if (payment > 0) {
// To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
// baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
}
emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
}
/// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
/// Note: The fees are always transferred, even if the user transaction fails.
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @param safeTxGas Gas that should be used for the Safe transaction.
/// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Gas price that should be used for the payment calculation.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
function execTransaction(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures
) public payable virtual returns (bool success) {
bytes32 txHash;
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
bytes memory txHashData =
encodeTransactionData(
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
nonce
);
// Increase nonce and execute transaction.
nonce++;
txHash = keccak256(txHashData);
checkSignatures(txHash, txHashData, signatures);
}
address guard = getGuard();
{
if (guard != address(0)) {
Guard(guard).checkTransaction(
// Transaction info
to,
value,
data,
operation,
safeTxGas,
// Payment info
baseGas,
gasPrice,
gasToken,
refundReceiver,
// Signature info
signatures,
msg.sender
);
}
}
// We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
// We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
// Use scope here to limit variable lifetime and prevent `stack too deep` errors
{
uint256 gasUsed = gasleft();
// If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
// We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
gasUsed = gasUsed.sub(gasleft());
// If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
// This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
// We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
uint256 payment = 0;
if (gasPrice > 0) {
payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
}
if (success) emit ExecutionSuccess(txHash, payment);
else emit ExecutionFailure(txHash, payment);
}
{
if (guard != address(0)) {
Guard(guard).checkAfterExecution(txHash, success);
}
}
}
function handlePayment(
uint256 gasUsed,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver
) private returns (uint256 payment) {
// solhint-disable-next-line avoid-tx-origin
address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
if (gasToken == address(0)) {
// For ETH we will only adjust the gas price to not be higher than the actual used gas price
payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
require(receiver.send(payment), "GS011");
} else {
payment = gasUsed.add(baseGas).mul(gasPrice);
require(transferToken(gasToken, receiver, payment), "GS012");
}
}
/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
*/
function checkSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures
) public view {
// Load threshold to avoid multiple storage loads
uint256 _threshold = threshold;
// Check that a threshold is set
require(_threshold > 0, "GS001");
checkNSignatures(dataHash, data, signatures, _threshold);
}
/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
* @param requiredSignatures Amount of required valid signatures.
*/
function checkNSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures,
uint256 requiredSignatures
) public view {
// Check that the provided signature data is not too short
require(signatures.length >= requiredSignatures.mul(65), "GS020");
// There cannot be an owner with address 0.
address lastOwner = address(0);
address currentOwner;
uint8 v;
bytes32 r;
bytes32 s;
uint256 i;
for (i = 0; i < requiredSignatures; i++) {
(v, r, s) = signatureSplit(signatures, i);
if (v == 0) {
// If v is 0 then it is a contract signature
// When handling contract signatures the address of the contract is encoded into r
currentOwner = address(uint160(uint256(r)));
// Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
// This check is not completely accurate, since it is possible that more signatures than the threshold are send.
// Here we only check that the pointer is not pointing inside the part that is being processed
require(uint256(s) >= requiredSignatures.mul(65), "GS021");
// Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
require(uint256(s).add(32) <= signatures.length, "GS022");
// Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
uint256 contractSignatureLen;
// solhint-disable-next-line no-inline-assembly
assembly {
contractSignatureLen := mload(add(add(signatures, s), 0x20))
}
require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
// Check signature
bytes memory contractSignature;
// solhint-disable-next-line no-inline-assembly
assembly {
// The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
contractSignature := add(add(signatures, s), 0x20)
}
require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
} else if (v == 1) {
// If v is 1 then it is an approved hash
// When handling approved hashes the address of the approver is encoded into r
currentOwner = address(uint160(uint256(r)));
// Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
} else if (v > 30) {
// If v > 30 then default va (27,28) has been adjusted for eth_sign flow
// To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s);
} else {
// Default is the ecrecover flow with the provided data hash
// Use ecrecover with the messageHash for EOA signatures
currentOwner = ecrecover(dataHash, v, r, s);
}
require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
lastOwner = currentOwner;
}
}
/// @dev Allows to estimate a Safe transaction.
/// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
/// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
/// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
function requiredTxGas(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) external returns (uint256) {
uint256 startGas = gasleft();
// We don't provide an error message here, as we use it to return the estimate
require(execute(to, value, data, operation, gasleft()));
uint256 requiredGas = startGas - gasleft();
// Convert response to string and return via error message
revert(string(abi.encodePacked(requiredGas)));
}
/**
* @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
* @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
*/
function approveHash(bytes32 hashToApprove) external {
require(owners[msg.sender] != address(0), "GS030");
approvedHashes[msg.sender][hashToApprove] = 1;
emit ApproveHash(hashToApprove, msg.sender);
}
/// @dev Returns the chain id used by this contract.
function getChainId() public view returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function domainSeparator() public view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
}
/// @dev Returns the bytes that are hashed to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Gas that should be used for the safe transaction.
/// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash bytes.
function encodeTransactionData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes memory) {
bytes32 safeTxHash =
keccak256(
abi.encode(
SAFE_TX_TYPEHASH,
to,
value,
keccak256(data),
operation,
safeTxGas,
baseGas,
gasPrice,
gasToken,
refundReceiver,
_nonce
)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
}
/// @dev Returns hash to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Fas that should be used for the safe transaction.
/// @param baseGas Gas costs for data used to trigger the safe transaction.
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash.
function getTransactionHash(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes32) {
return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
/// @title Executor - A contract that can execute transactions
/// @author Richard Meissner - <[email protected]>
contract Executor {
function execute(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 txGas
) internal returns (bool success) {
if (operation == Enum.Operation.DelegateCall) {
// solhint-disable-next-line no-inline-assembly
assembly {
success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
}
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/SelfAuthorized.sol";
/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <[email protected]>
contract FallbackManager is SelfAuthorized {
event ChangedFallbackHandler(address handler);
// keccak256("fallback_manager.handler.address")
bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
function internalSetFallbackHandler(address handler) internal {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, handler)
}
}
/// @dev Allows to add a contract to handle fallback calls.
/// Only fallback calls without value and with data will be forwarded.
/// This can only be done via a Safe transaction.
/// @param handler contract to handle fallback calls.
function setFallbackHandler(address handler) public authorized {
internalSetFallbackHandler(handler);
emit ChangedFallbackHandler(handler);
}
// solhint-disable-next-line payable-fallback,no-complex-fallback
fallback() external {
bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
let handler := sload(slot)
if iszero(handler) {
return(0, 0)
}
calldatacopy(0, 0, calldatasize())
// The msg.sender address is shifted to the left by 12 bytes to remove the padding
// Then the address without padding is stored right after the calldata
mstore(calldatasize(), shl(96, caller()))
// Add 20 bytes for the address appended add the end
let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
returndatacopy(0, 0, returndatasize())
if iszero(success) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
import "../interfaces/IERC165.sol";
interface Guard is IERC165 {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
}
abstract contract BaseGuard is Guard {
function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
return
interfaceId == type(Guard).interfaceId || // 0xe6d7a83a
interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
}
}
/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <[email protected]>
contract GuardManager is SelfAuthorized {
event ChangedGuard(address guard);
// keccak256("guard_manager.guard.address")
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/// @dev Set a guard that checks transactions before execution
/// @param guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address guard) external authorized {
if (guard != address(0)) {
require(Guard(guard).supportsInterface(type(Guard).interfaceId), "GS300");
}
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, guard)
}
emit ChangedGuard(guard);
}
function getGuard() internal view returns (address guard) {
bytes32 slot = GUARD_STORAGE_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
guard := sload(slot)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
import "./Executor.sol";
/// @title Module Manager - A contract that manages modules that can execute transactions via this contract
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract ModuleManager is SelfAuthorized, Executor {
event EnabledModule(address module);
event DisabledModule(address module);
event ExecutionFromModuleSuccess(address indexed module);
event ExecutionFromModuleFailure(address indexed module);
address internal constant SENTINEL_MODULES = address(0x1);
mapping(address => address) internal modules;
function setupModules(address to, bytes memory data) internal {
require(modules[SENTINEL_MODULES] == address(0), "GS100");
modules[SENTINEL_MODULES] = SENTINEL_MODULES;
if (to != address(0))
// Setup has to complete successfully or transaction fails.
require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
}
/// @dev Allows to add a module to the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Enables the module `module` for the Safe.
/// @param module Module to be whitelisted.
function enableModule(address module) public authorized {
// Module address cannot be null or sentinel.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
// Module cannot be added twice.
require(modules[module] == address(0), "GS102");
modules[module] = modules[SENTINEL_MODULES];
modules[SENTINEL_MODULES] = module;
emit EnabledModule(module);
}
/// @dev Allows to remove a module from the whitelist.
/// This can only be done via a Safe transaction.
/// @notice Disables the module `module` for the Safe.
/// @param prevModule Module that pointed to the module to be removed in the linked list
/// @param module Module to be removed.
function disableModule(address prevModule, address module) public authorized {
// Validate module address and check that it corresponds to module index.
require(module != address(0) && module != SENTINEL_MODULES, "GS101");
require(modules[prevModule] == module, "GS103");
modules[prevModule] = modules[module];
modules[module] = address(0);
emit DisabledModule(module);
}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public virtual returns (bool success) {
// Only whitelisted modules are allowed.
require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
// Execute transaction without further confirmations.
success = execute(to, value, data, operation, gasleft());
if (success) emit ExecutionFromModuleSuccess(msg.sender);
else emit ExecutionFromModuleFailure(msg.sender);
}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModuleReturnData(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public returns (bool success, bytes memory returnData) {
success = execTransactionFromModule(to, value, data, operation);
// solhint-disable-next-line no-inline-assembly
assembly {
// Load free memory location
let ptr := mload(0x40)
// We allocate memory for the return data by setting the free memory location to
// current free memory location + data size + 32 bytes for data size value
mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
// Store the size
mstore(ptr, returndatasize())
// Store the data
returndatacopy(add(ptr, 0x20), 0, returndatasize())
// Point the return data to the correct memory location
returnData := ptr
}
}
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) public view returns (bool) {
return SENTINEL_MODULES != module && modules[module] != address(0);
}
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
// Init array with max page size
array = new address[](pageSize);
// Populate return array
uint256 moduleCount = 0;
address currentModule = modules[start];
while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
array[moduleCount] = currentModule;
currentModule = modules[currentModule];
moduleCount++;
}
next = currentModule;
// Set correct size of returned array
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(array, moduleCount)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "../common/SelfAuthorized.sol";
/// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract OwnerManager is SelfAuthorized {
event AddedOwner(address owner);
event RemovedOwner(address owner);
event ChangedThreshold(uint256 threshold);
address internal constant SENTINEL_OWNERS = address(0x1);
mapping(address => address) internal owners;
uint256 internal ownerCount;
uint256 internal threshold;
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
function setupOwners(address[] memory _owners, uint256 _threshold) internal {
// Threshold can only be 0 at initialization.
// Check ensures that setup function can only be called once.
require(threshold == 0, "GS200");
// Validate that threshold is smaller than number of added owners.
require(_threshold <= _owners.length, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
// Initializing Safe owners.
address currentOwner = SENTINEL_OWNERS;
for (uint256 i = 0; i < _owners.length; i++) {
// Owner address cannot be null.
address owner = _owners[i];
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204");
owners[currentOwner] = owner;
currentOwner = owner;
}
owners[currentOwner] = SENTINEL_OWNERS;
ownerCount = _owners.length;
threshold = _threshold;
}
/// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
/// @param owner New owner address.
/// @param _threshold New threshold.
function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[owner] == address(0), "GS204");
owners[owner] = owners[SENTINEL_OWNERS];
owners[SENTINEL_OWNERS] = owner;
ownerCount++;
emit AddedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}
/// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
/// @param prevOwner Owner that pointed to the owner to be removed in the linked list
/// @param owner Owner address to be removed.
/// @param _threshold New threshold.
function removeOwner(
address prevOwner,
address owner,
uint256 _threshold
) public authorized {
// Only allow to remove an owner, if threshold can still be reached.
require(ownerCount - 1 >= _threshold, "GS201");
// Validate owner address and check that it corresponds to owner index.
require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == owner, "GS205");
owners[prevOwner] = owners[owner];
owners[owner] = address(0);
ownerCount--;
emit RemovedOwner(owner);
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
}
/// @dev Allows to swap/replace an owner from the Safe with another address.
/// This can only be done via a Safe transaction.
/// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
/// @param oldOwner Owner address to be replaced.
/// @param newOwner New owner address.
function swapOwner(
address prevOwner,
address oldOwner,
address newOwner
) public authorized {
// Owner address cannot be null, the sentinel or the Safe itself.
require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
// No duplicate owners allowed.
require(owners[newOwner] == address(0), "GS204");
// Validate oldOwner address and check that it corresponds to owner index.
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
require(owners[prevOwner] == oldOwner, "GS205");
owners[newOwner] = owners[oldOwner];
owners[prevOwner] = newOwner;
owners[oldOwner] = address(0);
emit RemovedOwner(oldOwner);
emit AddedOwner(newOwner);
}
/// @dev Allows to update the number of required confirmations by Safe owners.
/// This can only be done via a Safe transaction.
/// @notice Changes the threshold of the Safe to `_threshold`.
/// @param _threshold New threshold.
function changeThreshold(uint256 _threshold) public authorized {
// Validate that threshold is smaller than number of owners.
require(_threshold <= ownerCount, "GS201");
// There has to be at least one Safe owner.
require(_threshold >= 1, "GS202");
threshold = _threshold;
emit ChangedThreshold(threshold);
}
function getThreshold() public view returns (uint256) {
return threshold;
}
function isOwner(address owner) public view returns (bool) {
return owner != SENTINEL_OWNERS && owners[owner] != address(0);
}
/// @dev Returns array of owners.
/// @return Array of Safe owners.
function getOwners() public view returns (address[] memory) {
address[] memory array = new address[](ownerCount);
// populate return array
uint256 index = 0;
address currentOwner = owners[SENTINEL_OWNERS];
while (currentOwner != SENTINEL_OWNERS) {
array[index] = currentOwner;
currentOwner = owners[currentOwner];
index++;
}
return array;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Enum - Collection of enums
/// @author Richard Meissner - <[email protected]>
contract Enum {
enum Operation {Call, DelegateCall}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
/// @author Richard Meissner - <[email protected]>
contract EtherPaymentFallback {
event SafeReceived(address indexed sender, uint256 value);
/// @dev Fallback function accepts Ether transactions.
receive() external payable {
emit SafeReceived(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SecuredTokenTransfer - Secure token transfer
/// @author Richard Meissner - <[email protected]>
contract SecuredTokenTransfer {
/// @dev Transfers a token and returns if it was a success
/// @param token Token that should be transferred
/// @param receiver Receiver to whom the token should be transferred
/// @param amount The amount of tokens that should be transferred
function transferToken(
address token,
address receiver,
uint256 amount
) internal returns (bool transferred) {
// 0xa9059cbb - keccack("transfer(address,uint256)")
bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
// solhint-disable-next-line no-inline-assembly
assembly {
// We write the return value to scratch space.
// See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
switch returndatasize()
case 0 {
transferred := success
}
case 0x20 {
transferred := iszero(or(iszero(success), iszero(mload(0))))
}
default {
transferred := 0
}
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SelfAuthorized - authorizes current contract to perform actions
/// @author Richard Meissner - <[email protected]>
contract SelfAuthorized {
function requireSelfCall() private view {
require(msg.sender == address(this), "GS031");
}
modifier authorized() {
// This is a function call as it minimized the bytecode size
requireSelfCall();
_;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title SignatureDecoder - Decodes signatures that a encoded as bytes
/// @author Richard Meissner - <[email protected]>
contract SignatureDecoder {
/// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
/// @notice Make sure to perform a bounds check for @param pos, to avoid out of bounds access on @param signatures
/// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
/// @param signatures concatenated rsv signatures
function signatureSplit(bytes memory signatures, uint256 pos)
internal
pure
returns (
uint8 v,
bytes32 r,
bytes32 s
)
{
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
// solhint-disable-next-line no-inline-assembly
assembly {
let signaturePos := mul(0x41, pos)
r := mload(add(signatures, add(signaturePos, 0x20)))
s := mload(add(signatures, add(signaturePos, 0x40)))
// Here we are loading the last 32 bytes, including 31 bytes
// of 's'. There is no 'mload8' to do this.
//
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Singleton - Base for singleton contracts (should always be first super contract)
/// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
/// @author Richard Meissner - <[email protected]>
contract Singleton {
// singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
// It should also always be ensured that the address is stored alone (uses a full word)
address private singleton;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
/// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
contract StorageAccessible {
/**
* @dev Reads `length` bytes of storage in the currents contract
* @param offset - the offset in the current contract's storage in words to start reading from
* @param length - the number of words (32 bytes) of data to read
* @return the bytes that were read.
*/
function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
bytes memory result = new bytes(length * 32);
for (uint256 index = 0; index < length; index++) {
// solhint-disable-next-line no-inline-assembly
assembly {
let word := sload(add(offset, index))
mstore(add(add(result, 0x20), mul(index, 0x20)), word)
}
}
return result;
}
/**
* @dev Performs a delegatecall on a targetContract in the context of self.
* Internally reverts execution to avoid side effects (making it static).
*
* This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
* Specifically, the `returndata` after a call to this method will be:
* `success:bool || response.length:uint256 || response:bytes`.
*
* @param targetContract Address of the contract containing the code to execute.
* @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
*/
function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
// solhint-disable-next-line no-inline-assembly
assembly {
let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
mstore(0x00, success)
mstore(0x20, returndatasize())
returndatacopy(0x40, 0, returndatasize())
revert(0, add(returndatasize(), 0x40))
}
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/**
* @title GnosisSafeMath
* @dev Math operations with safety checks that revert on error
* Renamed from SafeMath to GnosisSafeMath to avoid conflicts
* TODO: remove once open zeppelin update to solc 0.5.0
*/
library GnosisSafeMath {
/**
* @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 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 Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
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: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
contract ISignatureValidatorConstants {
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
}
abstract contract ISignatureValidator is ISignatureValidatorConstants {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*
* MUST return the bytes4 magic value 0x20c13b0b when function passes.
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
}
|
Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. dataHash Hash of the data (could be either a message hash or transaction hash) data That should be signed (this is passed to an external validator contract) signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash./ Load threshold to avoid multiple storage loads Check that a threshold is set
|
function checkSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures
) public view {
uint256 _threshold = threshold;
require(_threshold > 0, "GS001");
checkNSignatures(dataHash, data, signatures, _threshold);
}
| 431,252 |
./full_match/1/0x12AAD8dAb7189C5EAa9aF79c2ea274413Ce1E332/sources/contracts/Distirbutor.sol
|
Set reward rate for rebase _rewardRate New rate
|
function setRate(uint256 _rewardRate) external onlyOwner {
require(
_rewardRate <= rateDenominator,
"Rate cannot exceed denominator"
);
rate = _rewardRate;
}
| 2,929,501 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract KaliToken {
// Public variables of the token
string public name = "KALI TOKEN";
string public symbol = "KAL";
uint8 public decimals = 0;
// 18 decimals is the strongly suggested default
uint256 public totalSupply;
uint256 public kaliSupply = 20000000;
uint256 public price ;
address public creator;
// 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);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function KaliToken() public {
totalSupply = kaliSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give KaliToken Mint the total created tokens
creator = msg.sender;
}
/**
* 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]);
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/// @notice Buy tokens from contract by sending ether
function () payable internal {
if (price >= 0 ether && price < 0.005 ether){
uint ammount = 2000; // calculates the amount, made it so you can get many KaliToken but to get MANY KaliToken you have to spend ETH and not WEI
uint ammountRaised;
amountRaised += msg.value; //many thanks kali, couldnt do it without r/me_irl
require(balanceOf[creator] >= ammount); // checks if it has enough to sell
require(msg.value < 0.1 ether); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing
balanceOf[msg.sender] += ammount; // adds the amount to buyer's balance
balanceOf[creator] -= ammount; // sends ETH to KaliXMinth
Transfer(creator, msg.sender, ammount); // execute an event reflecting the change
creator.transfer(ammountRaised);
}
if (price >= 0.005 ether && price < 0.03 ether){
uint amount = 2000; // calculates the amount, made it so you can get many KaliToken but to get MANY KaliToken you have to spend ETH and not WEI
uint amountRaised;
amountRaised += msg.value; //many thanks kali, couldnt do it without r/me_irl
require(balanceOf[creator] >= amount); // checks if it has enough to sell
require(msg.value < 0.1 ether); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing
balanceOf[msg.sender] += amount; // adds the amount to buyer's balance
balanceOf[creator] -= amount; // sends ETH to KaliXMinth
Transfer(creator, msg.sender, amount); // execute an event reflecting the change
creator.transfer(ammountRaised);
}
if (price >= 0.03 ether){
uint amnount = 10000; // calculates the amount, made it so you can get many KaliToken but to get MANY you have to spend ETH and not WEI
uint amnountRaised;
amountRaised += msg.value; //many thanks kalix, couldnt do it without r/me_irl
require(balanceOf[creator] >= amnount); // checks if it has enough to sell
require(msg.value < 0.1 ether); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing
balanceOf[msg.sender] += amnount; // adds the amount to buyer's balance
balanceOf[creator] -= amnount; // sends ETH to KaliXMinth
Transfer(creator, msg.sender, amnount); // execute an event reflecting the change
creator.transfer(amnountRaised);
}
}
}
|
Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
|
function KaliToken() public {
creator = msg.sender;
}
| 10,967,091 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { OVM_FraudContributor } from "./OVM_FraudContributor.sol";
/**
* @title OVM_StateTransitioner
*/
contract OVM_StateTransitioner is OVM_FraudContributor, iOVM_StateTransitioner, Lib_AddressResolver {
/*******************
* Data Structures *
*******************/
enum TransitionPhase {
PRE_EXECUTION,
POST_EXECUTION,
COMPLETE
}
/*******************************************
* Contract Variables: Contract References *
*******************************************/
iOVM_ExecutionManager internal ovmExecutionManager;
iOVM_StateManager internal ovmStateManager;
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
bytes32 internal preStateRoot;
bytes32 internal postStateRoot;
TransitionPhase internal phase;
uint256 internal stateTransitionIndex;
bytes32 internal transactionHash;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
*/
constructor(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
Lib_AddressResolver(_libAddressManager)
{
stateTransitionIndex = _stateTransitionIndex;
preStateRoot = _preStateRoot;
postStateRoot = _preStateRoot;
transactionHash = _transactionHash;
ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager"));
ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")).create(address(this));
ovmBondManager = iOVM_BondManager(resolve("OVM_BondManager"));
}
/**********************
* Function Modifiers *
**********************/
/**
* Checks that a function is only run during a specific phase.
* @param _phase Phase the function must run within.
*/
modifier onlyDuringPhase(
TransitionPhase _phase
) {
require(
phase == _phase,
"Function must be called during the correct phase."
);
_;
}
/**********************************
* Public Functions: State Access *
**********************************/
/**
* Retrieves the state root before execution.
* @return _preStateRoot State root before execution.
*/
function getPreStateRoot()
override
public
view
returns (
bytes32 _preStateRoot
)
{
return preStateRoot;
}
/**
* Retrieves the state root after execution.
* @return _postStateRoot State root after execution.
*/
function getPostStateRoot()
override
public
view
returns (
bytes32 _postStateRoot
)
{
return postStateRoot;
}
/**
* Checks whether the transitioner is complete.
* @return _complete Whether or not the transition process is finished.
*/
function isComplete()
override
public
view
returns (
bool _complete
)
{
return phase == TransitionPhase.COMPLETE;
}
/***********************************
* Public Functions: Pre-Execution *
***********************************/
/**
* Allows a user to prove the initial state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _account Claimed account state.
* @param _stateTrieWitness Proof of the account state.
*/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
Lib_OVMCodec.EVMAccount memory _account,
bytes memory _stateTrieWitness
)
override
public
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasAccount(_ovmContractAddress) == false,
"Account state has already been proven"
);
require(
_account.codeHash == Lib_EthUtils.getCodeHash(_ethContractAddress),
"Invalid code hash provided."
);
require(
Lib_SecureMerkleTrie.verifyInclusionProof(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(_account),
_stateTrieWitness,
preStateRoot
),
"Account state is not correct or invalid inclusion proof provided."
);
ovmStateManager.putAccount(
_ovmContractAddress,
Lib_OVMCodec.Account({
nonce: _account.nonce,
balance: _account.balance,
storageRoot: _account.storageRoot,
codeHash: _account.codeHash,
ethAddress: _ethContractAddress,
isFresh: false
})
);
}
/**
* Allows a user to prove that an account does *not* exist in the state.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _stateTrieWitness Proof of the (empty) account state.
*/
function proveEmptyContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
public
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false,
"Account state has already been proven."
);
require(
Lib_SecureMerkleTrie.verifyExclusionProof(
abi.encodePacked(_ovmContractAddress),
_stateTrieWitness,
preStateRoot
),
"Account is not empty or invalid inclusion proof provided."
);
ovmStateManager.putEmptyAccount(_ovmContractAddress);
}
/**
* Allows a user to prove the initial state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _value Claimed account slot value.
* @param _storageTrieWitness Proof of the storage slot.
*/
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes32 _value,
bytes memory _storageTrieWitness
)
override
public
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false,
"Storage slot has already been proven."
);
require(
ovmStateManager.hasAccount(_ovmContractAddress) == true,
"Contract must be verified before proving a storage slot."
);
(
bool exists,
bytes memory value
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_key),
_storageTrieWitness,
ovmStateManager.getAccountStorageRoot(_ovmContractAddress)
);
if (exists == true) {
require(
keccak256(value) == keccak256(abi.encodePacked(_value)),
"Provided storage slot value is invalid."
);
} else {
require(
_value == bytes32(0),
"Provided storage slot value is invalid."
);
}
ovmStateManager.putContractStorage(
_ovmContractAddress,
_key,
_value
);
}
/*******************************
* Public Functions: Execution *
*******************************/
/**
* Executes the state transition.
* @param _transaction OVM transaction to execute.
*/
function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
public
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot)
{
require(
Lib_OVMCodec.hashTransaction(_transaction) == transactionHash,
"Invalid transaction provided."
);
// We call `setExecutionManager` right before `run` (and not earlier) just in case the
// OVM_ExecutionManager address was updated between the time when this contract was created
// and when `applyTransaction` was called.
ovmStateManager.setExecutionManager(resolve("OVM_ExecutionManager"));
// `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction`
// or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line
// if that's the case.
ovmExecutionManager.run(_transaction, address(ovmStateManager));
phase = TransitionPhase.POST_EXECUTION;
}
/************************************
* Public Functions: Post-Execution *
************************************/
/**
* Allows a user to commit the final state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _stateTrieWitness Proof of the account state.
*/
function commitContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
public
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot)
{
require(
ovmStateManager.commitAccount(_ovmContractAddress) == true,
"Account was not changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
postStateRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(
Lib_OVMCodec.toEVMAccount(account)
),
_stateTrieWitness,
postStateRoot
);
}
/**
* Allows a user to commit the final state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _stateTrieWitness Proof of the account state.
* @param _storageTrieWitness Proof of the storage slot.
*/
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _stateTrieWitness,
bytes memory _storageTrieWitness
)
override
public
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot)
{
require(
ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true,
"Storage slot was not changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key);
account.storageRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_key),
abi.encodePacked(value),
_storageTrieWitness,
account.storageRoot
);
postStateRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(
Lib_OVMCodec.toEVMAccount(account)
),
_stateTrieWitness,
postStateRoot
);
ovmStateManager.putAccount(_ovmContractAddress, account);
}
/**********************************
* Public Functions: Finalization *
**********************************/
/**
* Finalizes the transition process.
*/
function completeTransition()
override
public
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
{
require(
ovmStateManager.getTotalUncommittedAccounts() == 0,
"All accounts must be committed before completing a transition."
);
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before completing a transition."
);
phase = TransitionPhase.COMPLETE;
}
}
|
Allows a user to prove that an account does not exist in the state. _ovmContractAddress Address of the contract on the OVM. _stateTrieWitness Proof of the (empty) account state./ Exit quickly to avoid unnecessary work.
|
function proveEmptyContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
public
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot)
{
require(
ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false,
"Account state has already been proven."
);
require(
Lib_SecureMerkleTrie.verifyExclusionProof(
abi.encodePacked(_ovmContractAddress),
_stateTrieWitness,
preStateRoot
),
"Account is not empty or invalid inclusion proof provided."
);
ovmStateManager.putEmptyAccount(_ovmContractAddress);
}
| 7,288,546 |
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/lib/prb-math/src/ud60x18/Math.sol
|
Divides two UD60x18 numbers, returning a new UD60x18 number. Uses {Common.mulDiv} to enable overflow-safe multiplication and division. Notes: - Refer to the notes in {Common.mulDiv}. Requirements: - Refer to the requirements in {Common.mulDiv}. x The numerator as a UD60x18 number. y The denominator as a UD60x18 number. result The quotient as a UD60x18 number. @custom:smtchecker abstract-function-nondet
|
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}
| 9,308,614 |
// File: contracts/AvastarTypes.sol
pragma solidity 0.5.14;
/**
* @title Avastar Data Types
* @author Cliff Hall
*/
contract AvastarTypes {
enum Generation {
ONE,
TWO,
THREE,
FOUR,
FIVE
}
enum Series {
PROMO,
ONE,
TWO,
THREE,
FOUR,
FIVE
}
enum Wave {
PRIME,
REPLICANT
}
enum Gene {
SKIN_TONE,
HAIR_COLOR,
EYE_COLOR,
BG_COLOR,
BACKDROP,
EARS,
FACE,
NOSE,
MOUTH,
FACIAL_FEATURE,
EYES,
HAIR_STYLE
}
enum Gender {
ANY,
MALE,
FEMALE
}
enum Rarity {
COMMON,
UNCOMMON,
RARE,
EPIC,
LEGENDARY
}
struct Trait {
uint256 id;
Generation generation;
Gender gender;
Gene gene;
Rarity rarity;
uint8 variation;
Series[] series;
string name;
string svg;
}
struct Prime {
uint256 id;
uint256 serial;
uint256 traits;
bool[12] replicated;
Generation generation;
Series series;
Gender gender;
uint8 ranking;
}
struct Replicant {
uint256 id;
uint256 serial;
uint256 traits;
Generation generation;
Gender gender;
uint8 ranking;
}
struct Avastar {
uint256 id;
uint256 serial;
uint256 traits;
Generation generation;
Wave wave;
}
struct Attribution {
Generation generation;
string artist;
string infoURI;
}
}
// File: contracts/AvastarBase.sol
pragma solidity 0.5.14;
/**
* @title Avastar Base
* @author Cliff Hall
* @notice Utilities used by descendant contracts
*/
contract AvastarBase {
/**
* @notice Convert a `uint` value to a `string`
* via OraclizeAPI - MIT licence
* https://github.com/provable-things/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol#L896
* @param _i the `uint` value to be converted
* @return result the `string` representation of the given `uint` value
*/
function uintToStr(uint _i)
internal pure
returns (string memory result) {
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;
}
result = string(bstr);
}
/**
* @notice Concatenate two strings
* @param _a the first string
* @param _b the second string
* @return result the concatenation of `_a` and `_b`
*/
function strConcat(string memory _a, string memory _b)
internal pure
returns(string memory result) {
result = string(abi.encodePacked(bytes(_a), bytes(_b)));
}
}
// File: @openzeppelin/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @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];
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/AccessControl.sol
pragma solidity 0.5.14;
/**
* @title Access Control
* @author Cliff Hall
* @notice Role-based access control and contract upgrade functionality.
*/
contract AccessControl {
using SafeMath for uint256;
using SafeMath for uint16;
using Roles for Roles.Role;
Roles.Role private admins;
Roles.Role private minters;
Roles.Role private owners;
/**
* @notice Sets `msg.sender` as system admin by default.
* Starts paused. System admin must unpause, and add other roles after deployment.
*/
constructor() public {
admins.add(msg.sender);
}
/**
* @notice Emitted when contract is paused by system administrator.
*/
event ContractPaused();
/**
* @notice Emitted when contract is unpaused by system administrator.
*/
event ContractUnpaused();
/**
* @notice Emitted when contract is upgraded by system administrator.
* @param newContract address of the new version of the contract.
*/
event ContractUpgrade(address newContract);
bool public paused = true;
bool public upgraded = false;
address public newContractAddress;
/**
* @notice Modifier to scope access to minters
*/
modifier onlyMinter() {
require(minters.has(msg.sender));
_;
}
/**
* @notice Modifier to scope access to owners
*/
modifier onlyOwner() {
require(owners.has(msg.sender));
_;
}
/**
* @notice Modifier to scope access to system administrators
*/
modifier onlySysAdmin() {
require(admins.has(msg.sender));
_;
}
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @notice Modifier to make a function callable only when the contract not upgraded.
*/
modifier whenNotUpgraded() {
require(!upgraded);
_;
}
/**
* @notice Called by a system administrator to mark the smart contract as upgraded,
* in case there is a serious breaking bug. This method stores the new contract
* address and emits an event to that effect. Clients of the contract should
* update to the new contract address upon receiving this event. This contract will
* remain paused indefinitely after such an upgrade.
* @param _newAddress address of new contract
*/
function upgradeContract(address _newAddress) external onlySysAdmin whenPaused whenNotUpgraded {
require(_newAddress != address(0));
upgraded = true;
newContractAddress = _newAddress;
emit ContractUpgrade(_newAddress);
}
/**
* @notice Called by a system administrator to add a minter.
* Reverts if `_minterAddress` already has minter role
* @param _minterAddress approved minter
*/
function addMinter(address _minterAddress) external onlySysAdmin {
minters.add(_minterAddress);
require(minters.has(_minterAddress));
}
/**
* @notice Called by a system administrator to add an owner.
* Reverts if `_ownerAddress` already has owner role
* @param _ownerAddress approved owner
* @return added boolean indicating whether the role was granted
*/
function addOwner(address _ownerAddress) external onlySysAdmin {
owners.add(_ownerAddress);
require(owners.has(_ownerAddress));
}
/**
* @notice Called by a system administrator to add another system admin.
* Reverts if `_sysAdminAddress` already has sysAdmin role
* @param _sysAdminAddress approved owner
*/
function addSysAdmin(address _sysAdminAddress) external onlySysAdmin {
admins.add(_sysAdminAddress);
require(admins.has(_sysAdminAddress));
}
/**
* @notice Called by an owner to remove all roles from an address.
* Reverts if address had no roles to be removed.
* @param _address address having its roles stripped
*/
function stripRoles(address _address) external onlyOwner {
require(msg.sender != _address);
bool stripped = false;
if (admins.has(_address)) {
admins.remove(_address);
stripped = true;
}
if (minters.has(_address)) {
minters.remove(_address);
stripped = true;
}
if (owners.has(_address)) {
owners.remove(_address);
stripped = true;
}
require(stripped == true);
}
/**
* @notice Called by a system administrator to pause, triggers stopped state
*/
function pause() external onlySysAdmin whenNotPaused {
paused = true;
emit ContractPaused();
}
/**
* @notice Called by a system administrator to un-pause, returns to normal state
*/
function unpause() external onlySysAdmin whenPaused whenNotUpgraded {
paused = false;
emit ContractUnpaused();
}
}
// File: @openzeppelin/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: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.5.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
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);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.5.0;
/**
* @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 {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 returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/drafts/Counters.sol
pragma solidity ^0.5.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity ^0.5.0;
/**
* @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) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
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].current();
}
/**
* @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 = _tokenOwner[tokenId];
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(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"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 != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), 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 {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), 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 {IERC721Receiver-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 {IERC721Receiver-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 _msgSender() 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 {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @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) internal {
_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 = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
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 safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} 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].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This function is deprecated.
* @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 (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), 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);
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721Enumerable.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
/*
* 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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @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 {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} 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 {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 = _ownedTokens[from].length.sub(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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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.sub(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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721Metadata.sol
pragma solidity ^0.5.0;
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* 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;
/**
* @dev Constructor function
*/
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_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @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 by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721Full.sol
pragma solidity ^0.5.0;
/**
* @title Full ERC721 Token
* @dev This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology.
*
* See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
// File: contracts/AvastarState.sol
pragma solidity 0.5.14;
/**
* @title Avastar State
* @author Cliff Hall
* @notice This contract maintains the state variables for the Avastar Teleporter.
*/
contract AvastarState is AvastarBase, AvastarTypes, AccessControl, ERC721Full {
/**
* @notice Calls ERC721Full constructor with token name and symbol.
*/
constructor() public ERC721Full(TOKEN_NAME, TOKEN_SYMBOL) {}
string public constant TOKEN_NAME = "Avastar";
string public constant TOKEN_SYMBOL = "AVASTAR";
/**
* @notice All Avastars across all Waves and Generations
*/
Avastar[] internal avastars;
/**
* @notice List of all Traits across all Generations
*/
Trait[] internal traits;
/**
* @notice Retrieve Primes by Generation
* Prime[] primes = primesByGeneration[uint8(_generation)]
*/
mapping(uint8 => Prime[]) internal primesByGeneration;
/**
* @notice Retrieve Replicants by Generation
* Replicant[] replicants = replicantsByGeneration[uint8(_generation)]
*/
mapping(uint8 => Replicant[]) internal replicantsByGeneration;
/**
* @notice Retrieve Artist Attribution by Generation
* Attribution attribution = attributionByGeneration[Generation(_generation)]
*/
mapping(uint8 => Attribution) public attributionByGeneration;
/**
* @notice Retrieve the approved Trait handler for a given Avastar Prime by Token ID
*/
mapping(uint256 => address) internal traitHandlerByPrimeTokenId;
/**
* @notice Is a given Trait Hash used within a given Generation
* bool used = isHashUsedByGeneration[uint8(_generation)][uint256(_traits)]
* This mapping ensures that within a Generation, a given Trait Hash is unique and can only be used once
*/
mapping(uint8 => mapping(uint256 => bool)) public isHashUsedByGeneration;
/**
* @notice Retrieve Token ID for a given Trait Hash within a given Generation
* uint256 tokenId = tokenIdByGenerationAndHash[uint8(_generation)][uint256(_traits)]
* Since Token IDs start at 0 and empty mappings for uint256 return 0, check isHashUsedByGeneration first
*/
mapping(uint8 => mapping(uint256 => uint256)) public tokenIdByGenerationAndHash;
/**
* @notice Retrieve count of Primes and Promos by Generation and Series
* uint16 count = primeCountByGenAndSeries[uint8(_generation)][uint8(_series)]
*/
mapping(uint8 => mapping(uint8 => uint16)) public primeCountByGenAndSeries;
/**
* @notice Retrieve count of Replicants by Generation
* uint16 count = replicantCountByGeneration[uint8(_generation)]
*/
mapping(uint8 => uint16) public replicantCountByGeneration;
/**
* @notice Retrieve the Token ID for an Avastar by a given Generation, Wave, and Serial
* uint256 tokenId = tokenIdByGenerationWaveAndSerial[uint8(_generation)][uint256(_wave)][uint256(_serial)]
*/
mapping(uint8 => mapping(uint8 => mapping(uint256 => uint256))) public tokenIdByGenerationWaveAndSerial;
/**
* @notice Retrieve the Trait ID for a Trait from a given Generation by Gene and Variation
* uint256 traitId = traitIdByGenerationGeneAndVariation[uint8(_generation)][uint8(_gene)][uint8(_variation)]
*/
mapping(uint8 => mapping(uint8 => mapping(uint8 => uint256))) public traitIdByGenerationGeneAndVariation;
}
// File: contracts/TraitFactory.sol
pragma solidity 0.5.14;
/**
* @title Avastar Trait Factory
* @author Cliff Hall
*/
contract TraitFactory is AvastarState {
/**
* @notice Event emitted when a new Trait is created.
* @param id the Trait ID
* @param generation the generation of the trait
* @param gene the gene that the trait is a variation of
* @param rarity the rarity level of this trait
* @param variation variation of the gene the trait represents
* @param name the name of the trait
*/
event NewTrait(uint256 id, Generation generation, Gene gene, Rarity rarity, uint8 variation, string name);
/**
* @notice Event emitted when artist attribution is set for a generation.
* @param generation the generation that attribution was set for
* @param artist the artist who created the artwork for the generation
* @param infoURI the artist's website / portfolio URI
*/
event AttributionSet(Generation generation, string artist, string infoURI);
/**
* @notice Event emitted when a Trait's art is created.
* @param id the Trait ID
*/
event TraitArtExtended(uint256 id);
/**
* @notice Modifier to ensure no trait modification after a generation's
* Avastar production has begun.
* @param _generation the generation to check production status of
*/
modifier onlyBeforeProd(Generation _generation) {
require(primesByGeneration[uint8(_generation)].length == 0 && replicantsByGeneration[uint8(_generation)].length == 0);
_;
}
/**
* @notice Get Trait ID by Generation, Gene, and Variation.
* @param _generation the generation the trait belongs to
* @param _gene gene the trait belongs to
* @param _variation the variation of the gene
* @return traitId the ID of the specified trait
*/
function getTraitIdByGenerationGeneAndVariation(
Generation _generation,
Gene _gene,
uint8 _variation
)
external view
returns (uint256 traitId)
{
return traitIdByGenerationGeneAndVariation[uint8(_generation)][uint8(_gene)][_variation];
}
/**
* @notice Retrieve a Trait's info by ID.
* @param _traitId the ID of the Trait to retrieve
* @return id the ID of the trait
* @return generation generation of the trait
* @return series list of series the trait may appear in
* @return gender gender(s) the trait is valid for
* @return gene gene the trait belongs to
* @return variation variation of the gene the trait represents
* @return rarity the rarity level of this trait
* @return name name of the trait
*/
function getTraitInfoById(uint256 _traitId)
external view
returns (
uint256 id,
Generation generation,
Series[] memory series,
Gender gender,
Gene gene,
Rarity rarity,
uint8 variation,
string memory name
) {
require(_traitId < traits.length);
Trait memory trait = traits[_traitId];
return (
trait.id,
trait.generation,
trait.series,
trait.gender,
trait.gene,
trait.rarity,
trait.variation,
trait.name
);
}
/**
* @notice Retrieve a Trait's name by ID.
* @param _traitId the ID of the Trait to retrieve
* @return name name of the trait
*/
function getTraitNameById(uint256 _traitId)
external view
returns (string memory name) {
require(_traitId < traits.length);
name = traits[_traitId].name;
}
/**
* @notice Retrieve a Trait's art by ID.
* Only invokable by a system administrator.
* @param _traitId the ID of the Trait to retrieve
* @return art the svg layer representation of the trait
*/
function getTraitArtById(uint256 _traitId)
external view onlySysAdmin
returns (string memory art) {
require(_traitId < traits.length);
Trait memory trait = traits[_traitId];
art = trait.svg;
}
/**
* @notice Get the artist Attribution info for a given Generation, combined into a single string.
* @param _generation the generation to retrieve artist attribution for
* @return attrib a single string with the artist and artist info URI
*/
function getAttributionByGeneration(Generation _generation)
external view
returns (
string memory attribution
){
Attribution memory attrib = attributionByGeneration[uint8(_generation)];
require(bytes(attrib.artist).length > 0);
attribution = strConcat(attribution, attrib.artist);
attribution = strConcat(attribution, ' (');
attribution = strConcat(attribution, attrib.infoURI);
attribution = strConcat(attribution, ')');
}
/**
* @notice Set the artist Attribution for a given Generation
* @param _generation the generation to set artist attribution for
* @param _artist the artist who created the art for the generation
* @param _infoURI the URI for the artist's website / portfolio
*/
function setAttribution(
Generation _generation,
string calldata _artist,
string calldata _infoURI
)
external onlySysAdmin onlyBeforeProd(_generation)
{
require(bytes(_artist).length > 0 && bytes(_infoURI).length > 0);
attributionByGeneration[uint8(_generation)] = Attribution(_generation, _artist, _infoURI);
emit AttributionSet(_generation, _artist, _infoURI);
}
/**
* @notice Create a Trait
* @param _generation the generation the trait belongs to
* @param _series list of series the trait may appear in
* @param _gender gender the trait is valid for
* @param _gene gene the trait belongs to
* @param _rarity the rarity level of this trait
* @param _variation the variation of the gene the trait belongs to
* @param _name the name of the trait
* @param _svg svg layer representation of the trait
* @return traitId the token ID of the newly created trait
*/
function createTrait(
Generation _generation,
Series[] calldata _series,
Gender _gender,
Gene _gene,
Rarity _rarity,
uint8 _variation,
string calldata _name,
string calldata _svg
)
external onlySysAdmin whenNotPaused onlyBeforeProd(_generation)
returns (uint256 traitId)
{
require(_series.length > 0);
require(bytes(_name).length > 0);
require(bytes(_svg).length > 0);
// Get Trait ID
traitId = traits.length;
// Create and store trait
traits.push(
Trait(traitId, _generation, _gender, _gene, _rarity, _variation, _series, _name, _svg)
);
// Create generation/gene/variation to traitId mapping required by assembleArtwork
traitIdByGenerationGeneAndVariation[uint8(_generation)][uint8(_gene)][uint8(_variation)] = traitId;
// Send the NewTrait event
emit NewTrait(traitId, _generation, _gene, _rarity, _variation, _name);
// Return the new Trait ID
return traitId;
}
/**
* @notice Extend a Trait's art.
* Only invokable by a system administrator.
* If successful, emits a `TraitArtExtended` event with the resultant artwork.
* @param _traitId the ID of the Trait to retrieve
* @param _svg the svg content to be concatenated to the existing svg property
*/
function extendTraitArt(uint256 _traitId, string calldata _svg)
external onlySysAdmin whenNotPaused onlyBeforeProd(traits[_traitId].generation)
{
require(_traitId < traits.length);
string memory art = strConcat(traits[_traitId].svg, _svg);
traits[_traitId].svg = art;
emit TraitArtExtended(_traitId);
}
/**
* @notice Assemble the artwork for a given Trait hash with art from the given Generation
* @param _generation the generation the Avastar belongs to
* @param _traitHash the Avastar's trait hash
* @return svg the fully rendered SVG for the Avastar
*/
function assembleArtwork(Generation _generation, uint256 _traitHash)
internal view
returns (string memory svg)
{
require(_traitHash > 0);
string memory accumulator = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="1000px" width="1000px" viewBox="0 0 1000 1000">';
uint256 slotConst = 256;
uint256 slotMask = 255;
uint256 bitMask;
uint256 slottedValue;
uint256 slotMultiplier;
uint256 variation;
uint256 traitId;
Trait memory trait;
// Iterate trait hash by Gene and assemble SVG sandwich
for (uint8 slot = 0; slot <= uint8(Gene.HAIR_STYLE); slot++){
slotMultiplier = uint256(slotConst**slot); // Create slot multiplier
bitMask = slotMask * slotMultiplier; // Create bit mask for slot
slottedValue = _traitHash & bitMask; // Extract slotted value from hash
if (slottedValue > 0) {
variation = (slot > 0) // Extract variation from slotted value
? slottedValue / slotMultiplier
: slottedValue;
if (variation > 0) {
traitId = traitIdByGenerationGeneAndVariation[uint8(_generation)][slot][uint8(variation)];
trait = traits[traitId];
accumulator = strConcat(accumulator, trait.svg);
}
}
}
return strConcat(accumulator, '</svg>');
}
}
// File: contracts/AvastarFactory.sol
pragma solidity 0.5.14;
/**
* @title Avastar Token Factory
* @author Cliff Hall
*/
contract AvastarFactory is TraitFactory {
/**
* @notice Mint an Avastar.
* Only invokable by descendant contracts when contract is not paused.
* Adds new `Avastar` to `avastars` array.
* Doesn't emit an event, the calling method does (`NewPrime` or `NewReplicant`).
* Sets `isHashUsedByGeneration` mapping to true for `avastar.generation` and `avastar.traits`.
* Sets `tokenIdByGenerationAndHash` mapping to `avastar.id` for `avastar.generation` and `avastar.traits`.
* Sets `tokenIdByGenerationWaveAndSerial` mapping to `avastar.id` for `avastar.generation`, `avastar.wave`, and `avastar.serial`.
* @param _owner the address of the new Avastar's owner
* @param _serial the new Avastar's Prime or Replicant serial number
* @param _traits the new Avastar's trait hash
* @param _generation the new Avastar's generation
* @param _wave the new Avastar's wave (Prime/Replicant)
* @return tokenId the newly minted Prime's token ID
*/
function mintAvastar(
address _owner,
uint256 _serial,
uint256 _traits,
Generation _generation,
Wave _wave
)
internal whenNotPaused
returns (uint256 tokenId)
{
// Mapped Token Id for given generation and serial should always be 0 (uninitialized)
require(tokenIdByGenerationWaveAndSerial[uint8(_generation)][uint8(_wave)][_serial] == 0);
// Serial should always be the current length of the primes or replicants array for the given generation
if (_wave == Wave.PRIME){
require(_serial == primesByGeneration[uint8(_generation)].length);
} else {
require(_serial == replicantsByGeneration[uint8(_generation)].length);
}
// Get Token ID
tokenId = avastars.length;
// Create and store Avastar token
Avastar memory avastar = Avastar(tokenId, _serial, _traits, _generation, _wave);
// Store the avastar
avastars.push(avastar);
// Indicate use of Trait Hash within given generation
isHashUsedByGeneration[uint8(avastar.generation)][avastar.traits] = true;
// Store token ID by Generation and Trait Hash
tokenIdByGenerationAndHash[uint8(avastar.generation)][avastar.traits] = avastar.id;
// Create generation/wave/serial to tokenId mapping
tokenIdByGenerationWaveAndSerial[uint8(avastar.generation)][uint8(avastar.wave)][avastar.serial] = avastar.id;
// Mint the token
super._mint(_owner, tokenId);
}
/**
* @notice Get an Avastar's Wave by token ID.
* @param _tokenId the token id of the given Avastar
* @return wave the Avastar's wave (Prime/Replicant)
*/
function getAvastarWaveByTokenId(uint256 _tokenId)
external view
returns (Wave wave)
{
require(_tokenId < avastars.length);
wave = avastars[_tokenId].wave;
}
/**
* @notice Render the Avastar Prime or Replicant from the original on-chain art.
* @param _tokenId the token ID of the Prime or Replicant
* @return svg the fully rendered SVG representation of the Avastar
*/
function renderAvastar(uint256 _tokenId)
external view
returns (string memory svg)
{
require(_tokenId < avastars.length);
Avastar memory avastar = avastars[_tokenId];
uint256 traits = (avastar.wave == Wave.PRIME)
? primesByGeneration[uint8(avastar.generation)][avastar.serial].traits
: replicantsByGeneration[uint8(avastar.generation)][avastar.serial].traits;
svg = assembleArtwork(avastar.generation, traits);
}
}
// File: contracts/PrimeFactory.sol
pragma solidity 0.5.14;
/**
* @title Avastar Prime Factory
* @author Cliff Hall
*/
contract PrimeFactory is AvastarFactory {
/**
* @notice Maximum number of primes that can be minted in
* any given series for any generation.
*/
uint16 public constant MAX_PRIMES_PER_SERIES = 5000;
uint16 public constant MAX_PROMO_PRIMES_PER_GENERATION = 200;
/**
* @notice Event emitted upon the creation of an Avastar Prime
* @param id the token ID of the newly minted Prime
* @param serial the serial of the Prime
* @param generation the generation of the Prime
* @param series the series of the Prime
* @param gender the gender of the Prime
* @param traits the trait hash of the Prime
*/
event NewPrime(uint256 id, uint256 serial, Generation generation, Series series, Gender gender, uint256 traits);
/**
* @notice Get the Avastar Prime metadata associated with a given Generation and Serial.
* Does not include the trait replication flags.
* @param _generation the Generation of the Prime
* @param _serial the Serial of the Prime
* @return tokenId the Prime's token ID
* @return serial the Prime's serial
* @return traits the Prime's trait hash
* @return replicated the Prime's trait replication indicators
* @return generation the Prime's generation
* @return series the Prime's series
* @return gender the Prime's gender
* @return ranking the Prime's ranking
*/
function getPrimeByGenerationAndSerial(Generation _generation, uint256 _serial)
external view
returns (
uint256 tokenId,
uint256 serial,
uint256 traits,
Generation generation,
Series series,
Gender gender,
uint8 ranking
) {
require(_serial < primesByGeneration[uint8(_generation)].length);
Prime memory prime = primesByGeneration[uint8(_generation)][_serial];
return (
prime.id,
prime.serial,
prime.traits,
prime.generation,
prime.series,
prime.gender,
prime.ranking
);
}
/**
* @notice Get the Avastar Prime associated with a given Token ID.
* Does not include the trait replication flags.
* @param _tokenId the Token ID of the specified Prime
* @return tokenId the Prime's token ID
* @return serial the Prime's serial
* @return traits the Prime's trait hash
* @return generation the Prime's generation
* @return series the Prime's series
* @return gender the Prime's gender
* @return ranking the Prime's ranking
*/
function getPrimeByTokenId(uint256 _tokenId)
external view
returns (
uint256 tokenId,
uint256 serial,
uint256 traits,
Generation generation,
Series series,
Gender gender,
uint8 ranking
) {
require(_tokenId < avastars.length);
Avastar memory avastar = avastars[_tokenId];
require(avastar.wave == Wave.PRIME);
Prime memory prime = primesByGeneration[uint8(avastar.generation)][avastar.serial];
return (
prime.id,
prime.serial,
prime.traits,
prime.generation,
prime.series,
prime.gender,
prime.ranking
);
}
/**
* @notice Get an Avastar Prime's replication flags by token ID.
* @param _tokenId the token ID of the specified Prime
* @return tokenId the Prime's token ID
* @return replicated the Prime's trait replication flags
*/
function getPrimeReplicationByTokenId(uint256 _tokenId)
external view
returns (
uint256 tokenId,
bool[12] memory replicated
) {
require(_tokenId < avastars.length);
Avastar memory avastar = avastars[_tokenId];
require(avastar.wave == Wave.PRIME);
Prime memory prime = primesByGeneration[uint8(avastar.generation)][avastar.serial];
return (
prime.id,
prime.replicated
);
}
/**
* @notice Mint an Avastar Prime
* Only invokable by minter role, when contract is not paused.
* If successful, emits a `NewPrime` event.
* @param _owner the address of the new Avastar's owner
* @param _traits the new Prime's trait hash
* @param _generation the new Prime's generation
* @return _series the new Prime's series
* @param _gender the new Prime's gender
* @param _ranking the new Prime's rarity ranking
* @return tokenId the newly minted Prime's token ID
* @return serial the newly minted Prime's serial
*/
function mintPrime(
address _owner,
uint256 _traits,
Generation _generation,
Series _series,
Gender _gender,
uint8 _ranking
)
external onlyMinter whenNotPaused
returns (uint256 tokenId, uint256 serial)
{
require(_owner != address(0));
require(_traits != 0);
require(isHashUsedByGeneration[uint8(_generation)][_traits] == false);
require(_ranking > 0 && _ranking <= 100);
uint16 count = primeCountByGenAndSeries[uint8(_generation)][uint8(_series)];
if (_series != Series.PROMO) {
require(count < MAX_PRIMES_PER_SERIES);
} else {
require(count < MAX_PROMO_PRIMES_PER_GENERATION);
}
// Get Prime Serial and mint Avastar, getting tokenId
serial = primesByGeneration[uint8(_generation)].length;
tokenId = mintAvastar(_owner, serial, _traits, _generation, Wave.PRIME);
// Create and store Prime struct
bool[12] memory replicated;
primesByGeneration[uint8(_generation)].push(
Prime(tokenId, serial, _traits, replicated, _generation, _series, _gender, _ranking)
);
// Increment count for given Generation/Series
primeCountByGenAndSeries[uint8(_generation)][uint8(_series)]++;
// Send the NewPrime event
emit NewPrime(tokenId, serial, _generation, _series, _gender, _traits);
// Return the tokenId, serial
return (tokenId, serial);
}
}
// File: contracts/ReplicantFactory.sol
pragma solidity 0.5.14;
/**
* @title Avastar Replicant Factory
* @author Cliff Hall
*/
contract ReplicantFactory is PrimeFactory {
/**
* @notice Maximum number of Replicants that can be minted
* in any given generation.
*/
uint16 public constant MAX_REPLICANTS_PER_GENERATION = 25200;
/**
* @notice Event emitted upon the creation of an Avastar Replicant
* @param id the token ID of the newly minted Replicant
* @param serial the serial of the Replicant
* @param generation the generation of the Replicant
* @param gender the gender of the Replicant
* @param traits the trait hash of the Replicant
*/
event NewReplicant(uint256 id, uint256 serial, Generation generation, Gender gender, uint256 traits);
/**
* @notice Get the Avastar Replicant metadata associated with a given Generation and Serial
* @param _generation the generation of the specified Replicant
* @param _serial the serial of the specified Replicant
* @return tokenId the Replicant's token ID
* @return serial the Replicant's serial
* @return traits the Replicant's trait hash
* @return generation the Replicant's generation
* @return gender the Replicant's gender
* @return ranking the Replicant's ranking
*/
function getReplicantByGenerationAndSerial(Generation _generation, uint256 _serial)
external view
returns (
uint256 tokenId,
uint256 serial,
uint256 traits,
Generation generation,
Gender gender,
uint8 ranking
) {
require(_serial < replicantsByGeneration[uint8(_generation)].length);
Replicant memory replicant = replicantsByGeneration[uint8(_generation)][_serial];
return (
replicant.id,
replicant.serial,
replicant.traits,
replicant.generation,
replicant.gender,
replicant.ranking
);
}
/**
* @notice Get the Avastar Replicant associated with a given Token ID
* @param _tokenId the token ID of the specified Replicant
* @return tokenId the Replicant's token ID
* @return serial the Replicant's serial
* @return traits the Replicant's trait hash
* @return generation the Replicant's generation
* @return gender the Replicant's gender
* @return ranking the Replicant's ranking
*/
function getReplicantByTokenId(uint256 _tokenId)
external view
returns (
uint256 tokenId,
uint256 serial,
uint256 traits,
Generation generation,
Gender gender,
uint8 ranking
) {
require(_tokenId < avastars.length);
Avastar memory avastar = avastars[_tokenId];
require(avastar.wave == Wave.REPLICANT);
Replicant memory replicant = replicantsByGeneration[uint8(avastar.generation)][avastar.serial];
return (
replicant.id,
replicant.serial,
replicant.traits,
replicant.generation,
replicant.gender,
replicant.ranking
);
}
/**
* @notice Mint an Avastar Replicant.
* Only invokable by minter role, when contract is not paused.
* If successful, emits a `NewReplicant` event.
* @param _owner the address of the new Avastar's owner
* @param _traits the new Replicant's trait hash
* @param _generation the new Replicant's generation
* @param _gender the new Replicant's gender
* @param _ranking the new Replicant's rarity ranking
* @return tokenId the newly minted Replicant's token ID
* @return serial the newly minted Replicant's serial
*/
function mintReplicant(
address _owner,
uint256 _traits,
Generation _generation,
Gender _gender,
uint8 _ranking
)
external onlyMinter whenNotPaused
returns (uint256 tokenId, uint256 serial)
{
require(_traits != 0);
require(isHashUsedByGeneration[uint8(_generation)][_traits] == false);
require(_ranking > 0 && _ranking <= 100);
require(replicantCountByGeneration[uint8(_generation)] < MAX_REPLICANTS_PER_GENERATION);
// Get Replicant Serial and mint Avastar, getting tokenId
serial = replicantsByGeneration[uint8(_generation)].length;
tokenId = mintAvastar(_owner, serial, _traits, _generation, Wave.REPLICANT);
// Create and store Replicant struct
replicantsByGeneration[uint8(_generation)].push(
Replicant(tokenId, serial, _traits, _generation, _gender, _ranking)
);
// Increment count for given Generation
replicantCountByGeneration[uint8(_generation)]++;
// Send the NewReplicant event
emit NewReplicant(tokenId, serial, _generation, _gender, _traits);
// Return the tokenId, serial
return (tokenId, serial);
}
}
// File: contracts/IAvastarMetadata.sol
pragma solidity 0.5.14;
/**
* @title Identification interface for Avastar Metadata generator contract
* @author Cliff Hall
* @notice Used by `AvastarTeleporter` contract to validate the address of the contract.
*/
interface IAvastarMetadata {
/**
* @notice Acknowledge contract is `AvastarMetadata`
* @return always true
*/
function isAvastarMetadata() external pure returns (bool);
/**
* @notice Get token URI for a given Avastar Token ID.
* @param _tokenId the Token ID of a previously minted Avastar Prime or Replicant
* @return uri the Avastar's off-chain JSON metadata URI
*/
function tokenURI(uint _tokenId)
external view
returns (string memory uri);
}
// File: contracts/AvastarTeleporter.sol
pragma solidity 0.5.14;
/**
* @title AvastarTeleporter
* @author Cliff Hall
* @notice Management of Avastar Primes, Replicants, and Traits
*/
contract AvastarTeleporter is ReplicantFactory {
/**
* @notice Event emitted when a handler is approved to manage Trait replication.
* @param handler the address being approved to Trait replication
* @param primeIds the array of Avastar Prime tokenIds the handler can use
*/
event TraitAccessApproved(address indexed handler, uint256[] primeIds);
/**
* @notice Event emitted when a handler replicates Traits.
* @param handler the address marking the Traits as used
* @param primeId the token id of the Prime supplying the Traits
* @param used the array of flags representing the Primes resulting Trait usage
*/
event TraitsUsed(address indexed handler, uint256 primeId, bool[12] used);
/**
* @notice Event emitted when AvastarMetadata contract address is set
* @param contractAddress the address of the new AvastarMetadata contract
*/
event MetadataContractAddressSet(address contractAddress);
/**
* @notice Address of the AvastarMetadata contract
*/
address private metadataContractAddress;
/**
* @notice Acknowledge contract is `AvastarTeleporter`
* @return always true
*/
function isAvastarTeleporter() external pure returns (bool) {return true;}
/**
* @notice Set the address of the `AvastarMetadata` contract.
* Only invokable by system admin role, when contract is paused and not upgraded.
* If successful, emits an `MetadataContractAddressSet` event.
* @param _address address of AvastarTeleporter contract
*/
function setMetadataContractAddress(address _address)
external onlySysAdmin whenPaused whenNotUpgraded
{
// Cast the candidate contract to the IAvastarMetadata interface
IAvastarMetadata candidateContract = IAvastarMetadata(_address);
// Verify that we have the appropriate address
require(candidateContract.isAvastarMetadata());
// Set the contract address
metadataContractAddress = _address;
// Emit the event
emit MetadataContractAddressSet(_address);
}
/**
* @notice Get the current address of the `AvastarMetadata` contract.
* return contractAddress the address of the `AvastarMetadata` contract
*/
function getMetadataContractAddress()
external view
returns (address contractAddress) {
return metadataContractAddress;
}
/**
* @notice Get token URI for a given Avastar Token ID.
* Reverts if given token id is not a valid Avastar Token ID.
* @param _tokenId the Token ID of a previously minted Avastar Prime or Replicant
* @return uri the Avastar's off-chain JSON metadata URI
*/
function tokenURI(uint _tokenId)
external view
returns (string memory uri)
{
require(_tokenId < avastars.length);
return IAvastarMetadata(metadataContractAddress).tokenURI(_tokenId);
}
/**
* @notice Approve a handler to manage Trait replication for a set of Avastar Primes.
* Accepts up to 256 primes for approval per call.
* Reverts if caller is not owner of all Primes specified.
* Reverts if no Primes are specified.
* Reverts if given handler already has approval for all Primes specified.
* If successful, emits a `TraitAccessApproved` event.
* @param _handler the address approved for Trait access
* @param _primeIds the token ids for which to approve the handler
*/
function approveTraitAccess(address _handler, uint256[] calldata _primeIds)
external
{
require(_primeIds.length > 0 && _primeIds.length <= 256);
uint256 primeId;
bool approvedAtLeast1 = false;
for (uint8 i = 0; i < _primeIds.length; i++) {
primeId = _primeIds[i];
require(primeId < avastars.length);
require(msg.sender == super.ownerOf(primeId), "Must be token owner");
if (traitHandlerByPrimeTokenId[primeId] != _handler) {
traitHandlerByPrimeTokenId[primeId] = _handler;
approvedAtLeast1 = true;
}
}
require(approvedAtLeast1, "No unhandled primes specified");
// Emit the event
emit TraitAccessApproved(_handler, _primeIds);
}
/**
* @notice Mark some or all of an Avastar Prime's traits used.
* Caller must be the token owner OR the approved handler.
* Caller must send all 12 flags with those to be used set to true, the rest to false.
* The position of each flag in the `_traitFlags` array corresponds to a Gene, of which Traits are variations.
* The flag order is: [ SKIN_TONE, HAIR_COLOR, EYE_COLOR, BG_COLOR, BACKDROP, EARS, FACE, NOSE, MOUTH, FACIAL_FEATURE, EYES, HAIR_STYLE ].
* Reverts if no usable traits are indicated.
* If successful, emits a `TraitsUsed` event.
* @param _primeId the token id for the Prime whose Traits are to be used
* @param _traitFlags an array of no more than 12 booleans representing the Traits to be used
*/
function useTraits(uint256 _primeId, bool[12] calldata _traitFlags)
external
{
// Make certain token id is valid
require(_primeId < avastars.length);
// Make certain caller is token owner OR approved handler
require(msg.sender == super.ownerOf(_primeId) || msg.sender == traitHandlerByPrimeTokenId[_primeId],
"Must be token owner or approved handler" );
// Get the Avastar and make sure it's a Prime
Avastar memory avastar = avastars[_primeId];
require(avastar.wave == Wave.PRIME);
// Get the Prime
Prime storage prime = primesByGeneration[uint8(avastar.generation)][avastar.serial];
// Set the flags.
bool usedAtLeast1;
for (uint8 i = 0; i < 12; i++) {
if (_traitFlags.length > i ) {
if ( !prime.replicated[i] && _traitFlags[i] ) {
prime.replicated[i] = true;
usedAtLeast1 = true;
}
} else {
break;
}
}
// Revert if no flags changed
require(usedAtLeast1, "No reusable traits specified");
// Clear trait handler
traitHandlerByPrimeTokenId[_primeId] = address(0);
// Emit the TraitsUsed event
emit TraitsUsed(msg.sender, _primeId, prime.replicated);
}
}
|
Set the artist Attribution for a given Generation _generation the generation to set artist attribution for _artist the artist who created the art for the generation _infoURI the URI for the artist's website / portfolio/
|
function setAttribution(
Generation _generation,
string calldata _artist,
string calldata _infoURI
)
external onlySysAdmin onlyBeforeProd(_generation)
{
require(bytes(_artist).length > 0 && bytes(_infoURI).length > 0);
attributionByGeneration[uint8(_generation)] = Attribution(_generation, _artist, _infoURI);
emit AttributionSet(_generation, _artist, _infoURI);
}
| 1,082,500 |
//ZK-Exchange handles all ZK verification, note and order state management, token escrowing
pragma solidity ^0.5.0;
import "./interfaces/IERC20.sol";
import {Verifier as MintVerifier} from "./verifiers/CreateNoteVerifier.sol";
import {Verifier as SpendVerifier} from "./verifiers/SpendNoteVerifier.sol";
import {Verifier as ClaimVerifier} from "./verifiers/ClaimNoteVerifier.sol";
import {Verifier as CreateOrderVerifier} from "./verifiers/CreateOrderVerifier.sol";
import {Verifier as FillOrderVerifier} from "./verifiers/FillOrderVerifier.sol";
contract ZkExchange is MintVerifier, SpendVerifier, ClaimVerifier, CreateOrderVerifier, FillOrderVerifier {
enum NoteState {
INVALID,
MINTED,
SPENT,
EXCHANGABLE,
PENDING
}
struct Note {
uint256 timeCreated;
NoteState state;
// clients are responsible for storing private note fields, (e.g encrypted on IPFS)
}
enum OrderState {
INVALID,
CREATED,
FILLED,
VOIDED
}
struct Order {
uint256 timeCreated;
bytes32 makerNote; // pre-exchange note
bytes32 makerFillNote; // post-exchange note
OrderState state;
}
event Mint(bytes32 noteHash);
event Exchangeable(bytes32 noteHash);
event Spend(bytes32 noteHash);
event Claim(bytes32 noteHash, address token, uint256 value);
event CreateOrder(bytes32 orderHash, bytes32 makerNoteHash, bytes32 makerFillNoteHash);
event FillOrder(bytes32 orderHash, bytes32 takerFillNoteHash, bytes32 makerFillNoteHash);
mapping (bytes32 => Note) notes;
mapping (bytes32 => Order) orders;
function createOrder(
// snark params
uint256[2] calldata a,
uint256[2] calldata a_p,
uint256[2][2] calldata b,
uint256[2] calldata b_p,
uint256[2] calldata c,
uint256[2] calldata c_p,
uint256[2] calldata h,
uint256[2] calldata k,
//orderHash0, orderHash1, noteHash0, noteHash1, fillNoteHash0, fillNoteHash1, output
uint256[7] calldata publicParams
)
external
{
bytes32 orderHash = calcHash(publicParams[0], publicParams[1]);
bytes32 noteHash = calcHash(publicParams[2], publicParams[3]);
bytes32 fillNoteHash = calcHash(publicParams[4], publicParams[5]);
require(
notes[noteHash].state == NoteState.MINTED,
"Invalid maker note"
);
require(
notes[fillNoteHash].timeCreated == 0,
"Duplicate maker fill note exists"
);
require(
orders[orderHash].timeCreated == 0,
"Invalid or duplicate order"
);
require(
CreateOrderVerifier.verifyTx(a, a_p, b, b_p, c, c_p, h, k, publicParams),
"Invalid create order proof"
);
notes[noteHash].state = NoteState.EXCHANGABLE;
notes[fillNoteHash] = Note(now, NoteState.PENDING);
orders[orderHash] = Order(now, noteHash, fillNoteHash, OrderState.CREATED);
emit CreateOrder(orderHash, noteHash, fillNoteHash);
emit Exchangeable(noteHash);
}
function fillOrder(
// snark params
uint256[2] calldata a,
uint256[2] calldata a_p,
uint256[2][2] calldata b,
uint256[2] calldata b_p,
uint256[2] calldata c,
uint256[2] calldata c_p,
uint256[2] calldata h,
uint256[2] calldata k,
//orderHash0, orderHash1, noteHash0, noteHash1, fillNoteHash0, fillNoteHash1, output
uint256[7] calldata publicParams
)
external
{
bytes32 orderHash = calcHash(publicParams[0], publicParams[1]);
bytes32 takerNoteHash = calcHash(publicParams[2], publicParams[3]);
bytes32 takerFillNoteHash = calcHash(publicParams[4], publicParams[5]);
bytes32 makerNoteHash = orders[orderHash].makerNote;
bytes32 makerFillNoteHash = orders[orderHash].makerFillNote;
require(
orders[orderHash].state == OrderState.CREATED,
"Invalid order"
);
orders[orderHash].state = OrderState.FILLED;
// ensure maker note is exchangable
require(
notes[makerNoteHash].state == NoteState.EXCHANGABLE,
"Maker note invalid"
);
// ensure maker fill note is pending
require(
notes[makerFillNoteHash].state == NoteState.PENDING,
"Maker fill note invalid"
);
// ensure taker note is spendable
require(
notes[takerNoteHash].state == NoteState.MINTED,
"Invalid taker note"
);
// ensure taker fill note is not already in use
require(
notes[takerFillNoteHash].timeCreated == 0,
"Taker fill note is already minted or invalid"
);
// verify proof
require(
FillOrderVerifier.verifyTx(a, a_p, b, b_p, c, c_p, h, k, publicParams),
"Invalid fill order proof"
);
// spend maker and taker notes
notes[makerNoteHash].state = NoteState.SPENT;
notes[takerNoteHash].state = NoteState.SPENT;
// activate pending maker fill note
notes[makerFillNoteHash].state = NoteState.MINTED;
// mint taker fill note
notes[takerFillNoteHash] = Note(now, NoteState.MINTED);
// log order filled, order notes spent, and fill notes minted
emit FillOrder(orderHash, takerFillNoteHash, makerFillNoteHash);
emit Spend(makerNoteHash);
emit Spend(takerNoteHash);
emit Mint(takerFillNoteHash);
emit Mint(makerFillNoteHash);
}
function mintNote(
// snark params
uint256[2] calldata a,
uint256[2] calldata a_p,
uint256[2][2] calldata b,
uint256[2] calldata b_p,
uint256[2] calldata c,
uint256[2] calldata c_p,
uint256[2] calldata h,
uint256[2] calldata k,
//notehash0, notehash1, tokenaddr, value, output
uint256[5] calldata publicParams
)
external
{
bytes32 noteHash = calcHash(publicParams[0], publicParams[1]);
address token = address(publicParams[2]);
uint256 value = uint256(publicParams[3]);
// ensure note uniqueness
require(notes[noteHash].timeCreated == 0, "Note already minted");
// add note to registry
notes[noteHash] = Note(now, NoteState.MINTED);
// transfer tokens
require(
ERC20(token).transferFrom(msg.sender, address(this), value),
"Token transfer failed"
);
require(
MintVerifier.verifyTx(a, a_p, b, b_p, c, c_p, h, k, publicParams),
"Invalid mint proof"
);
emit Mint(noteHash);
}
function spendNote(
// snark params
uint256[2] calldata a,
uint256[2] calldata a_p,
uint256[2][2] calldata b,
uint256[2] calldata b_p,
uint256[2] calldata c,
uint256[2] calldata c_p,
uint256[2] calldata h,
uint256[2] calldata k,
//originalHash0, originalHash1, note0h0, note0h1, note1h0, note1h1, output
uint256[7] calldata publicParams
)
external
{
bytes32[3] memory noteRefs = get3Notes(publicParams);
require(notes[noteRefs[0]].state == NoteState.MINTED, "Note is either invalid or already spent");
require(notes[noteRefs[1]].state == NoteState.INVALID, "output note1 is already minted");
require(notes[noteRefs[2]].state == NoteState.INVALID, "output note2 is already minted");
require(
SpendVerifier.verifyTx(a, a_p, b, b_p, c, c_p, h, k, publicParams),
"Invalid spend proof"
);
notes[noteRefs[0]].state = NoteState.SPENT;
notes[noteRefs[1]] = Note(now, NoteState.MINTED);
notes[noteRefs[2]] = Note(now, NoteState.MINTED);
emit Spend(noteRefs[0]);
emit Mint(noteRefs[1]);
emit Mint(noteRefs[2]);
}
/**
* @dev consume note and transfer tokens to claimant
*/
function claimNote(
address to,
// snark params
uint256[2] calldata a,
uint256[2] calldata a_p,
uint256[2][2] calldata b,
uint256[2] calldata b_p,
uint256[2] calldata c,
uint256[2] calldata c_p,
uint256[2] calldata h,
uint256[2] calldata k,
//notehash0, notehash1, tokenaddr, value, output
uint256[5] calldata publicParams
)
external
{
bytes32 noteHash = calcHash(publicParams[0], publicParams[1]);
address token = address(publicParams[2]);
uint256 value = uint256(publicParams[3]);
// ensure note is minted and unspent
require(notes[noteHash].state == NoteState.MINTED, "Note already spent");
// mark note as spent
notes[noteHash].state == NoteState.SPENT;
require(
ERC20(token).transferFrom( address(this), to, value),
"Token transfer failed"
);
require(
ClaimVerifier.verifyTx(a, a_p, b, b_p, c, c_p, h, k, publicParams),
"Invalid claim proof"
);
}
function get3Notes(uint256[7] memory input)
internal
pure
returns(bytes32[3] memory _notes)
{
_notes[0] = calcHash(input[0], input[1]);
_notes[1] = calcHash(input[2], input[3]);
_notes[2] = calcHash(input[4], input[5]);
}
/**
* @dev Concatenates the 2 chunks of the sha256 hash of the note
* @notice This method is required due to the field limitations imposed by the zokrates zkSnark library
* @param _a Most significant 128 bits of the note hash
* @param _b Least significant 128 bits of the note hash
*/
function calcHash(uint256 _a, uint256 _b)
internal
pure
returns(bytes32 noteHash)
{
uint256 combinedHash = _a * (2 ** 16) + _b;
noteHash = bytes32(combinedHash);
}
}
|
snark paramsorderHash0, orderHash1, noteHash0, noteHash1, fillNoteHash0, fillNoteHash1, output ensure maker note is exchangable ensure maker fill note is pending ensure taker note is spendable ensure taker fill note is not already in use verify proof spend maker and taker notes activate pending maker fill note mint taker fill note log order filled, order notes spent, and fill notes minted
|
function fillOrder(
uint256[2] calldata a,
uint256[2] calldata a_p,
uint256[2][2] calldata b,
uint256[2] calldata b_p,
uint256[2] calldata c,
uint256[2] calldata c_p,
uint256[2] calldata h,
uint256[2] calldata k,
uint256[7] calldata publicParams
)
external
{
bytes32 orderHash = calcHash(publicParams[0], publicParams[1]);
bytes32 takerNoteHash = calcHash(publicParams[2], publicParams[3]);
bytes32 takerFillNoteHash = calcHash(publicParams[4], publicParams[5]);
bytes32 makerNoteHash = orders[orderHash].makerNote;
bytes32 makerFillNoteHash = orders[orderHash].makerFillNote;
require(
orders[orderHash].state == OrderState.CREATED,
"Invalid order"
);
orders[orderHash].state = OrderState.FILLED;
require(
notes[makerNoteHash].state == NoteState.EXCHANGABLE,
"Maker note invalid"
);
require(
notes[makerFillNoteHash].state == NoteState.PENDING,
"Maker fill note invalid"
);
require(
notes[takerNoteHash].state == NoteState.MINTED,
"Invalid taker note"
);
require(
notes[takerFillNoteHash].timeCreated == 0,
"Taker fill note is already minted or invalid"
);
require(
FillOrderVerifier.verifyTx(a, a_p, b, b_p, c, c_p, h, k, publicParams),
"Invalid fill order proof"
);
notes[makerNoteHash].state = NoteState.SPENT;
notes[takerNoteHash].state = NoteState.SPENT;
notes[makerFillNoteHash].state = NoteState.MINTED;
notes[takerFillNoteHash] = Note(now, NoteState.MINTED);
emit FillOrder(orderHash, takerFillNoteHash, makerFillNoteHash);
emit Spend(makerNoteHash);
emit Spend(takerNoteHash);
emit Mint(takerFillNoteHash);
emit Mint(makerFillNoteHash);
}
| 15,874,041 |
pragma solidity ^0.4.20;
/*
* ==================================== *
* *
* ========== https://powx.co ========= *
* *
* ==================================== *
* -> What?
* The original autonomous pyramid, improved:
* [x] More stable than ever, having withstood severe testnet abuse and attack attempts from our community!.
* [x] Audited, tested, and approved by known community security specialists such as tocsick and Arc.
* [X] New functionality; you can now perform partial sell orders. If you succumb to weak hands, you don't have to dump all of your bags!
* [x] New functionality; you can now transfer tokens between wallets. Trading is now possible from within the contract!
* [x] New Feature: PoS Masternodes! The first implementation of Ethereum Staking in the world! Vitalik is mad.
* [x] Masternodes: Holding 100 PoWX Tokens allow you to generate a Masternode link, Masternode links are used as unique entry points to the contract!
* [x] Masternodes: All players who enter the contract through your Masternode have 30% of their 15% dividends fee rerouted from the master-node, to the node-master!
*
* The dev team consists of seasoned, professional developers and has been audited by veteran solidity experts.
* Additionally, two independent testnet iterations have been used by hundreds of people; not a single point of failure was found.
*
*/
contract PowX {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "PowX";
string public symbol = "PWX";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 15;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 20 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function PowX()
public
{
// add administrators here
administrators[keccak256(msg.sender)] = true;
// add the ambassadors here.
ambassadors_[msg.sender] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 15% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 15% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Set Ambassadors
*/
function setAmbassadors(address ambassador, bool _status)
onlyAdministrator()
public
{
ambassadors_[ambassador] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
Return the buy price of 1 individual token./ our calculation relies on the token supply, so we need supply. Doh.
|
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
| 378,172 |
./full_match/80001/0x4444572f8e6FB8b76f2943C1ba15f5aA9b38eC72/sources/gist-4c970e79d3a27a9edbbf04d6c737be27/IInitializableDebtToken.sol
|
IInitializableDebtToken Aave Interface for the initialize function common between debt tokens/
|
interface IInitializableDebtToken {
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address incentivesController,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
function initialize(
IPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
pragma solidity ^0.8.0;
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
import {IPool} from './IPool.sol';
}
| 5,658,188 |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/// @dev Implements simple fixed point math add, sub, mul and div operations.
/// @author Alberto Cuesta Cañada
library DecimalMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
/// @dev Returns 1 in the fixed point representation, with `decimals` decimals.
function unit(uint8 decimals) internal pure returns (uint256) {
require(decimals <= 77, "Too many decimals");
return 10**uint256(decimals);
}
/// @dev Adds x and y, assuming they are both fixed point with 18 decimals.
function addd(uint256 x, uint256 y) internal pure returns (uint256) {
return x.add(y);
}
/// @dev Adds x and y, assuming they are both fixed point with 18 decimals.
function addd(int256 x, int256 y) internal pure returns (int256) {
return x.add(y);
}
/// @dev Substracts y from x, assuming they are both fixed point with 18 decimals.
function subd(uint256 x, uint256 y) internal pure returns (uint256) {
return x.sub(y);
}
/// @dev Substracts y from x, assuming they are both fixed point with 18 decimals.
function subd(int256 x, int256 y) internal pure returns (int256) {
return x.sub(y);
}
/// @dev Multiplies x and y, assuming they are both fixed point with 18 digits.
function muld(uint256 x, uint256 y) internal pure returns (uint256) {
return muld(x, y, 18);
}
/// @dev Multiplies x and y, assuming they are both fixed point with 18 digits.
function muld(int256 x, int256 y) internal pure returns (int256) {
return muld(x, y, 18);
}
/// @dev Multiplies x and y, assuming they are both fixed point with `decimals` digits.
function muld(uint256 x, uint256 y, uint8 decimals)
internal pure returns (uint256)
{
return x.mul(y).div(unit(decimals));
}
/// @dev Multiplies x and y, assuming they are both fixed point with `decimals` digits.
function muld(int256 x, int256 y, uint8 decimals)
internal pure returns (int256)
{
return x.mul(y).div(int256(unit(decimals)));
}
/// @dev Divides x between y, assuming they are both fixed point with 18 digits.
function divd(uint256 x, uint256 y) internal pure returns (uint256) {
return divd(x, y, 18);
}
/// @dev Divides x between y, assuming they are both fixed point with 18 digits.
function divd(int256 x, int256 y) internal pure returns (int256) {
return divd(x, y, 18);
}
/// @dev Divides x between y, assuming they are both fixed point with `decimals` digits.
function divd(uint256 x, uint256 y, uint8 decimals)
internal pure returns (uint256)
{
return x.mul(unit(decimals)).div(y);
}
/// @dev Divides x between y, assuming they are both fixed point with `decimals` digits.
function divd(int256 x, int256 y, uint8 decimals)
internal pure returns (int256)
{
return x.mul(int(unit(decimals))).div(y);
}
/// @dev Divides x between y, rounding to the closes representable number.
/// Assumes x and y are both fixed point with 18 digits.
function divdr(uint256 x, uint256 y) internal pure returns (uint256) {
return divdr(x, y, 18);
}
/// @dev Divides x between y, rounding to the closes representable number.
/// Assumes x and y are both fixed point with 18 digits.
function divdr(int256 x, int256 y) internal pure returns (int256) {
return divdr(x, y, 18);
}
/// @dev Divides x between y, rounding to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function divdr(uint256 x, uint256 y, uint8 decimals)
internal pure returns (uint256)
{
uint256 z = x.mul(unit(decimals + 1)).div(y);
if (z % 10 > 5) return z / 10 + 1;
else return z / 10;
}
/// @dev Divides x between y, rounding to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function divdr(int256 x, int256 y, uint8 decimals)
internal pure returns (int256)
{
int256 z = x.mul(int256(unit(decimals + 1))).div(y);
if (z % 10 > 5) return z / 10 + 1;
else if (z % 10 < -5) return z / 10 - 1;
else return z / 10;
}
/// @dev Divides x between y, rounding to the closes representable number.
/// Assumes x and y are both fixed point with 18 digits.
function divdrup(uint256 x, uint256 y) internal pure returns (uint256) {
return divdrup(x, y, 18);
}
/// @dev Divides x between y, rounding to the closes representable number.
/// Assumes x and y are both fixed point with 18 digits.
function divdrup(int256 x, int256 y) internal pure returns (int256) {
return divdrup(x, y, 18);
}
/// @dev Divides x between y, rounding to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function divdrup(uint256 x, uint256 y, uint8 decimals)
internal pure returns (uint256)
{
uint256 z = x.mul(unit(decimals + 1)).div(y);
if (z % 10 > 0) return z / 10 + 1;
else return z / 10;
}
/// @dev Divides x between y, rounding to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function divdrup(int256 x, int256 y, uint8 decimals)
internal pure returns (int256)
{
int256 z = x.mul(int256(unit(decimals + 1))).div(y);
if (z % 10 > 0) return z / 10 + 1;
else if (z % 10 < 0) return z / 10 - 1;
else return z / 10;
}
}
|
Divides x between y, assuming they are both fixed point with `decimals` digits.
|
function divd(int256 x, int256 y, uint8 decimals)
internal pure returns (int256)
{
return x.mul(int(unit(decimals))).div(y);
}
| 5,361,041 |
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol
|
Computes the {TimelockController} operation salt. It is computed with the governor address itself to avoid collisions across governor instances using the same timelock./
|
function _timelockSalt(bytes32 descriptionHash) private view returns (bytes32) {
return bytes20(address(this)) ^ descriptionHash;
}
| 8,083,792 |
pragma solidity ^0.5.0;
import "../ENS.sol";
import "../ResolverBase.sol";
// This is a special "trusted attesting" resolver, in the sense that some record info associated
// to a node can not be set by the owner of the node, but it has to be set by the
// owner of the parent node. In other words, the parent node "attests" that the information associated
// to a given node is correct (under the responsibility of the parent node owner).
// It acts as an extension to the assignment of a name to a node (setSubnodeOwner), which can only be
// made by the parent node and under its responsibility.
// This means that anyone resolving the info from the node name knows that the info has been verified
// by the owner of the parent node. This is extremely useful in many real-world environments where
// Trusted Entities are required to attest some other entities.
// In addition to the trusted info, there is "normal" information that can be set by the owner of the node.
//
// In particular:
// Attested info by the parent: DID, name and active
// Self-managed info: DIDDocument (the parent can set initially that info if desired, but it can be changed later)
contract AlaDIDPublicEntityResolver is ResolverBase {
// The EntityData includes:
// DID The DID of the entity.
// name The short name assigned to the entity.
// DIDDocument The associated DIDDocument in JSON-LD format.
// active A flag to allow pausing the entity.
struct EntityData {
bytes32 DIDHash;
string domain_name;
string DIDDocument;
bool active;
}
// The main registry of entities
// node => EntityData record
mapping(bytes32 => EntityData) entities;
// Fast resolution of DIDs
// DID => node
mapping(bytes32 => bytes32) nodes;
// Reverse resolution of addresses to nodes, without an additional smart contract
// address => node
mapping(address => bytes32) nodes_from_address;
// With the above structures, it is efficient to do the following:
// - From a DID, get the DID Document (W3C DID Resolution)
// - From an address, get the node and then the DID and DID Document
// This allows the usage of a standard address in any place, but efficienttly get the DID,
// if there is one associated.
// For companies and other public entities in the Alastria ecosystem, this should always be the case.
// - From a DID or address, get the domain name assigned in ENS.
// This assumes that the trusted entity registering the DID uses the domain name that is associated,
// via the name_hash algorithm, to the node and label parameters.
event AlaDIDDocumentChanged(bytes32 indexed node, string document);
// We specify both the node and the subnode ("label"), the caller should be the owner of the parent node.
// This is in contrast to "normal" resolvers, where only the target node is specified.
function setAlaDIDPublicEntity(
bytes32 node,
bytes32 label,
bytes32 _DIDHash,
string calldata _domain_name,
string calldata _DIDDocument,
bool _active,
address _owner
) external authorised(node) {
// Check for lengths of strings
require(bytes(_domain_name).length < 100, "Domain name too big");
require(bytes(_DIDDocument).length < 3000, "DID Document too big");
// Calculate the namehash of the subnode
bytes32 subnode = keccak256(abi.encodePacked(node, label));
// Assign ownership of the name to the specified address, via the ENS smart contract
_ens().setSubnodeOwner(node, label, _owner);
// Set the essential entity information for the subnode, that the subnode owner can not modify
entities[subnode] = EntityData(
_DIDHash,
_domain_name,
_DIDDocument,
_active
);
// Update the list of DIDs, for easy resolution later
nodes[_DIDHash] = subnode;
nodes_from_address[_owner] = subnode;
}
/**
* Returns the entity data associated with an ENS node.
* @param node The ENS node to query.
* @return The associated entity data.
*/
function AlaDIDPublicEntity(bytes32 node) external view returns (
bytes32 _DIDHash,
string memory _domain_name,
string memory _DIDDocument,
bool _active
) {
return (
entities[node].DIDHash,
entities[node].domain_name,
entities[node].DIDDocument,
entities[node].active
);
}
function nodeFromDID(bytes32 _DIDHash) external view returns (bytes32 _node) {
// Check for lengths of strings
return nodes[_DIDHash];
}
function addressFromDID(bytes32 _DIDHash) external view returns (address _owner) {
// Check for lengths of strings
bytes32 node = nodes[_DIDHash];
return _ens().owner(node);
}
/**
* Sets the AlaDIDDocument associated with the ENS node that has the given DID.
* May only be called by the owner of that node in the ENS registry.
* @param _DIDHash The hash of the DID to update.
* @param _DIDDocument The document to set.
*/
function setAlaDIDDocument(bytes32 _DIDHash, string calldata _DIDDocument) external {
// Check for lengths of strings
require(bytes(_DIDDocument).length < 2000, "DID Document too big");
// Get the associated node (if any)
bytes32 node = nodes[_DIDHash];
// The caller must be the owner of the node
require(isAuthorised(node), "Caller is NOT authorised");
// Set the document field in EntityData
entities[node].DIDDocument = _DIDDocument;
emit AlaDIDDocumentChanged(node, _DIDDocument);
}
}
|
We specify both the node and the subnode ("label"), the caller should be the owner of the parent node. This is in contrast to "normal" resolvers, where only the target node is specified. Check for lengths of strings Calculate the namehash of the subnode Assign ownership of the name to the specified address, via the ENS smart contract Set the essential entity information for the subnode, that the subnode owner can not modify Update the list of DIDs, for easy resolution later
|
function setAlaDIDPublicEntity(
bytes32 node,
bytes32 label,
bytes32 _DIDHash,
string calldata _domain_name,
string calldata _DIDDocument,
bool _active,
address _owner
) external authorised(node) {
require(bytes(_domain_name).length < 100, "Domain name too big");
require(bytes(_DIDDocument).length < 3000, "DID Document too big");
bytes32 subnode = keccak256(abi.encodePacked(node, label));
_ens().setSubnodeOwner(node, label, _owner);
entities[subnode] = EntityData(
_DIDHash,
_domain_name,
_DIDDocument,
_active
);
nodes[_DIDHash] = subnode;
nodes_from_address[_owner] = subnode;
}
| 1,085,867 |
./full_match/42220/0x4733612DF7f4dd34B0dD76D8eE45BBdA9b0Be8a4/sources/contracts/spaceswap-ubeswap/Factory.sol
|
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 = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
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(3).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
kLast = 0;
}
}
| 16,359,707 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ConfirmedOwner.sol";
import "./interfaces/AggregatorValidatorInterface.sol";
import "./interfaces/TypeAndVersionInterface.sol";
contract ValidatorProxy is AggregatorValidatorInterface, TypeAndVersionInterface, ConfirmedOwner {
/// @notice Uses a single storage slot to store the current address
struct AggregatorConfiguration {
address target;
bool hasNewProposal;
}
struct ValidatorConfiguration {
AggregatorValidatorInterface target;
bool hasNewProposal;
}
// Configuration for the current aggregator
AggregatorConfiguration private s_currentAggregator;
// Proposed aggregator address
address private s_proposedAggregator;
// Configuration for the current validator
ValidatorConfiguration private s_currentValidator;
// Proposed validator address
AggregatorValidatorInterface private s_proposedValidator;
event AggregatorProposed(address indexed aggregator);
event AggregatorUpgraded(address indexed previous, address indexed current);
event ValidatorProposed(AggregatorValidatorInterface indexed validator);
event ValidatorUpgraded(AggregatorValidatorInterface indexed previous, AggregatorValidatorInterface indexed current);
/// @notice The proposed aggregator called validate, but the call was not passed on to any validators
event ProposedAggregatorValidateCall(
address indexed proposed,
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
);
/**
* @notice Construct the ValidatorProxy with an aggregator and a validator
* @param aggregator address
* @param validator address
*/
constructor(address aggregator, AggregatorValidatorInterface validator) ConfirmedOwner(msg.sender) {
s_currentAggregator = AggregatorConfiguration({target: aggregator, hasNewProposal: false});
s_currentValidator = ValidatorConfiguration({target: validator, hasNewProposal: false});
}
/**
* @notice Validate a transmission
* @dev Must be called by either the `s_currentAggregator.target`, or the `s_proposedAggregator`.
* If called by the `s_currentAggregator.target` this function passes the call on to the `s_currentValidator.target`
* and the `s_proposedValidator`, if it is set.
* If called by the `s_proposedAggregator` this function emits a `ProposedAggregatorValidateCall` to signal that
* the call was received.
* @dev To guard against external `validate` calls reverting, we use raw calls here.
* We favour `call` over try-catch to ensure that failures are avoided even if the validator address is incorrectly
* set as a non-contract address.
* @dev If the `aggregator` and `validator` are the same contract or collude, this could exhibit reentrancy behavior.
* However, since that contract would have to be explicitly written for reentrancy and that the `owner` would have
* to configure this contract to use that malicious contract, we refrain from using mutex or check here.
* @dev This does not perform any checks on any roundId, so it is possible that a validator receive different reports
* for the same roundId at different points in time. Validator implementations should be aware of this.
* @param previousRoundId uint256
* @param previousAnswer int256
* @param currentRoundId uint256
* @param currentAnswer int256
* @return bool
*/
function validate(
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
) external override returns (bool) {
address currentAggregator = s_currentAggregator.target;
if (msg.sender != currentAggregator) {
address proposedAggregator = s_proposedAggregator;
require(msg.sender == proposedAggregator, "Not a configured aggregator");
// If the aggregator is still in proposed state, emit an event and don't push to any validator.
// This is to confirm that `validate` is being called prior to upgrade.
emit ProposedAggregatorValidateCall(
proposedAggregator,
previousRoundId,
previousAnswer,
currentRoundId,
currentAnswer
);
return true;
}
// Send the validate call to the current validator
ValidatorConfiguration memory currentValidator = s_currentValidator;
address currentValidatorAddress = address(currentValidator.target);
require(currentValidatorAddress != address(0), "No validator set");
currentValidatorAddress.call(
abi.encodeWithSelector(
AggregatorValidatorInterface.validate.selector,
previousRoundId,
previousAnswer,
currentRoundId,
currentAnswer
)
);
// If there is a new proposed validator, send the validate call to that validator also
if (currentValidator.hasNewProposal) {
address(s_proposedValidator).call(
abi.encodeWithSelector(
AggregatorValidatorInterface.validate.selector,
previousRoundId,
previousAnswer,
currentRoundId,
currentAnswer
)
);
}
return true;
}
/** AGGREGATOR CONFIGURATION FUNCTIONS **/
/**
* @notice Propose an aggregator
* @dev A zero address can be used to unset the proposed aggregator. Only owner can call.
* @param proposed address
*/
function proposeNewAggregator(address proposed) external onlyOwner {
require(s_proposedAggregator != proposed && s_currentAggregator.target != proposed, "Invalid proposal");
s_proposedAggregator = proposed;
// If proposed is zero address, hasNewProposal = false
s_currentAggregator.hasNewProposal = (proposed != address(0));
emit AggregatorProposed(proposed);
}
/**
* @notice Upgrade the aggregator by setting the current aggregator as the proposed aggregator.
* @dev Must have a proposed aggregator. Only owner can call.
*/
function upgradeAggregator() external onlyOwner {
// Get configuration in memory
AggregatorConfiguration memory current = s_currentAggregator;
address previous = current.target;
address proposed = s_proposedAggregator;
// Perform the upgrade
require(current.hasNewProposal, "No proposal");
s_currentAggregator = AggregatorConfiguration({target: proposed, hasNewProposal: false});
delete s_proposedAggregator;
emit AggregatorUpgraded(previous, proposed);
}
/**
* @notice Get aggregator details
* @return current address
* @return hasProposal bool
* @return proposed address
*/
function getAggregators()
external
view
returns (
address current,
bool hasProposal,
address proposed
)
{
current = s_currentAggregator.target;
hasProposal = s_currentAggregator.hasNewProposal;
proposed = s_proposedAggregator;
}
/** VALIDATOR CONFIGURATION FUNCTIONS **/
/**
* @notice Propose an validator
* @dev A zero address can be used to unset the proposed validator. Only owner can call.
* @param proposed address
*/
function proposeNewValidator(AggregatorValidatorInterface proposed) external onlyOwner {
require(s_proposedValidator != proposed && s_currentValidator.target != proposed, "Invalid proposal");
s_proposedValidator = proposed;
// If proposed is zero address, hasNewProposal = false
s_currentValidator.hasNewProposal = (address(proposed) != address(0));
emit ValidatorProposed(proposed);
}
/**
* @notice Upgrade the validator by setting the current validator as the proposed validator.
* @dev Must have a proposed validator. Only owner can call.
*/
function upgradeValidator() external onlyOwner {
// Get configuration in memory
ValidatorConfiguration memory current = s_currentValidator;
AggregatorValidatorInterface previous = current.target;
AggregatorValidatorInterface proposed = s_proposedValidator;
// Perform the upgrade
require(current.hasNewProposal, "No proposal");
s_currentValidator = ValidatorConfiguration({target: proposed, hasNewProposal: false});
delete s_proposedValidator;
emit ValidatorUpgraded(previous, proposed);
}
/**
* @notice Get validator details
* @return current address
* @return hasProposal bool
* @return proposed address
*/
function getValidators()
external
view
returns (
AggregatorValidatorInterface current,
bool hasProposal,
AggregatorValidatorInterface proposed
)
{
current = s_currentValidator.target;
hasProposal = s_currentValidator.hasNewProposal;
proposed = s_proposedValidator;
}
/**
* @notice The type and version of this contract
* @return Type and version string
*/
function typeAndVersion() external pure virtual override returns (string memory) {
return "ValidatorProxy 1.0.0";
}
}
|
Upgrade the aggregator by setting the current aggregator as the proposed aggregator. Must have a proposed aggregator. Only owner can call./ Get configuration in memory Perform the upgrade
|
function upgradeAggregator() external onlyOwner {
AggregatorConfiguration memory current = s_currentAggregator;
address previous = current.target;
address proposed = s_proposedAggregator;
require(current.hasNewProposal, "No proposal");
delete s_proposedAggregator;
emit AggregatorUpgraded(previous, proposed);
}
| 923,408 |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY643() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF605(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER78(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE980(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE90(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM630(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER779(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL135(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER484() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA848() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY643() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF605(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER78(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER916(_MSGSENDER484(), recipient, amount);
return true;
}
function ALLOWANCE980(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE90(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER484(), spender, amount);
return true;
}
function TRANSFERFROM630(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER916(sender, recipient, amount);
_APPROVE737(sender, _MSGSENDER484(), _allowances[sender][_MSGSENDER484()].SUB312(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE56(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER484(), spender, _allowances[_MSGSENDER484()][spender].ADD968(addedValue));
return true;
}
function DECREASEALLOWANCE957(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER484(), spender, _allowances[_MSGSENDER484()][spender].SUB312(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER916(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB312(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD968(amount);
emit TRANSFER779(sender, recipient, amount);
}
function _MINT550(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD968(amount);
_balances[account] = _balances[account].ADD968(amount);
emit TRANSFER779(address(0), account, amount);
}
function _BURN701(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB312(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB312(amount);
emit TRANSFER779(account, address(0), amount);
}
function _APPROVE737(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL135(owner, spender, amount);
}
function _BURNFROM514(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN701(account, amount);
_APPROVE737(account, _MSGSENDER484(), _allowances[account][_MSGSENDER484()].SUB312(amount, "ERC20: burn amount exceeds allowance"));
}
}
library SafeMath {
function ADD968(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB312(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB312(a, b, "SafeMath: subtraction overflow");
}
function SUB312(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 MUL309(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV143(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV143(a, b, "SafeMath: division by zero");
}
function DIV143(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;
return c;
}
function MOD945(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD945(a, b, "SafeMath: modulo by zero");
}
function MOD945(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT912(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE424(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE79(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER155(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.TRANSFER78.selector, to, value));
}
function SAFETRANSFERFROM711(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.TRANSFERFROM630.selector, from, to, value));
}
function SAFEAPPROVE528(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE980(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, value));
}
function SAFEINCREASEALLOWANCE603(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE980(address(this), spender).ADD968(value);
CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE308(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE980(address(this), spender).SUB312(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN172(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT912(), "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");
}
}
}
contract pLINKVault {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
struct RewardDivide {
mapping (address => uint256) amount;
uint256 time;
}
IERC20 public token = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA);
address public governance;
uint256 public totalDeposit;
mapping(address => uint256) public depositBalances;
mapping(address => uint256) public rewardBalances;
address[] public addressIndices;
mapping(uint256 => RewardDivide) public _rewards;
uint256 public _rewardCount = 0;
event WITHDRAWN572(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
constructor () public {
governance = msg.sender;
}
function BALANCE902() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF605(address(this));
}
function SETGOVERNANCE662(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function DEPOSITALL531() external { //inject NONSTANDARD NAMING
DEPOSIT826(token.BALANCEOF605(msg.sender));
}
function DEPOSIT826(uint256 _amount) public { //inject NONSTANDARD NAMING
require(_amount > 0, "can't deposit 0");
uint arrayLength = addressIndices.length;
bool found = false;
for (uint i = 0; i < arrayLength; i++) {
if(addressIndices[i]==msg.sender){
found=true;
break;
}
}
if(!found){
addressIndices.push(msg.sender);
}
uint256 realAmount = _amount.MUL309(995).DIV143(1000);
uint256 feeAmount = _amount.MUL309(5).DIV143(1000);
address feeAddress = 0xD319d5a9D039f06858263E95235575Bb0Bd630BC;
address vaultAddress = 0x32e4bD46e7cee1797b22B02c0340818B6e75C75a; // Vault7 Address
token.SAFETRANSFERFROM711(msg.sender, feeAddress, feeAmount);
token.SAFETRANSFERFROM711(msg.sender, vaultAddress, realAmount);
totalDeposit = totalDeposit.ADD968(realAmount);
depositBalances[msg.sender] = depositBalances[msg.sender].ADD968(realAmount);
}
function REWARD497(uint256 _amount) external { //inject NONSTANDARD NAMING
require(_amount > 0, "can't reward 0");
require(totalDeposit > 0, "totalDeposit must bigger than 0");
token.SAFETRANSFERFROM711(msg.sender, address(this), _amount);
uint arrayLength = addressIndices.length;
for (uint i = 0; i < arrayLength; i++) {
rewardBalances[addressIndices[i]] = rewardBalances[addressIndices[i]].ADD968(_amount.MUL309(depositBalances[addressIndices[i]]).DIV143(totalDeposit));
_rewards[_rewardCount].amount[addressIndices[i]] = _amount.MUL309(depositBalances[addressIndices[i]]).DIV143(totalDeposit);
}
_rewards[_rewardCount].time = block.timestamp;
_rewardCount++;
}
function WITHDRAWALL236() external { //inject NONSTANDARD NAMING
WITHDRAW435(rewardBalances[msg.sender]);
}
function WITHDRAW435(uint256 _amount) public { //inject NONSTANDARD NAMING
require(_rewardCount > 0, "no reward amount");
require(_amount > 0, "can't withdraw 0");
uint256 availableWithdrawAmount = AVAILABLEWITHDRAW912(msg.sender);
if (_amount > availableWithdrawAmount) {
_amount = availableWithdrawAmount;
}
token.SAFETRANSFER155(msg.sender, _amount);
rewardBalances[msg.sender] = rewardBalances[msg.sender].SUB312(_amount);
emit WITHDRAWN572(msg.sender, _amount);
}
function AVAILABLEWITHDRAW912(address owner) public view returns(uint256){ //inject NONSTANDARD NAMING
uint256 availableWithdrawAmount = rewardBalances[owner];
for (uint256 i = _rewardCount - 1; block.timestamp < _rewards[i].time.ADD968(7 days); --i) {
availableWithdrawAmount = availableWithdrawAmount.SUB312(_rewards[i].amount[owner].MUL309(_rewards[i].time.ADD968(7 days).SUB312(block.timestamp)).DIV143(7 days));
if (i == 0) break;
}
return availableWithdrawAmount;
}
}
|
inject NONSTANDARD NAMING
|
function SAFEAPPROVE528(IERC20 token, address spender, uint256 value) internal {
| 12,702,306 |
// contracts/Strawberries.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./ISeeds.sol";
import "./FruitsLibrary.sol";
contract Strawberries is ERC721Enumerable {
/**
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMWKkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkKWMMMMMMMMMMMM
MMMMMMMMWKOkdc'..................................'cdkOKWMMMMMMMM
MMMMMMWKx:...',;,'''''''''''''''''''''''''''''',;,'...:xKWMMMMMM
MMMMWKx:......',;;,,'''''''''''''''''''''''',,;;,'......:xKWMMMM
MMWKx:..........',;;,,,,,,,,,,,,,,,,,,,,,,,,;;,'..........:xKWMM
WKx:..............',;:;;;;;;;;;;;;;;;;;;;;:;,'..............:xKW
No............................................................oN
Xl. ..........''''''''''''''''''''''''''''''''''''.......... .lX
Xl. ........,oO0000000000000000000000000000000000Oo,........ .lX
Xl. ......,oOKKXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXKKOo,...... .lX
Xl. ... .:kKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKk:. ... .lX
Xl. ... .:OXXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXXO:. ... .lX
Xl. ... .:OXXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXXO:. ... .lX
Xl. ... .:OXXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXXO:. ... .lX
Xl. ... .:OXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXO:. ... .lX
Xl. ... .:OXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXO:. ... .lX
Xl. ... .:OXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXO:. ... .lX
Xl. ... .:OXXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXXO:. ... .lX
Xl. .....,oOKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKOo,..... .lX
Xl. ..... .c0XXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXX0c. ..... .lX
Xl. .......,oOKXKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKXKOo,....... .lX
Xl. .........,oOKXXKKKKKKKKKKKKKKKKKKKKKKKKKKXXKOo,......... .lX
Xl. ...........,oOKXKKKKKKKKKKKKKKKKKKKKKKKKXKOo,........... .lX
Xl. .............,oOKXXXXXXXXXXXXXXXXXXXXXXKOo,............. .lX
Nk:................,looooooooooooooooooooool,................:kN
MWKc. .................................................... .cKWM
MMNk:..............,;;;;;;;;;;;;;;;;;;;;;;;;,..............:kNMM
MMMWXx;.............','''''''''''''''''''','.............;xXWMMM
MMMMMWXx:...........''''''''''''''''''''''''...........:xXWMMMMM
MMMMMMMWXx:;,......................................,;:xXWMMMMMMM
MMMMMMMMMWNX0c. .c0XNWMMMMMMMMM
:cheese::astronaut::cheese: RIP 7767 :cheese::astronaut::cheese:
**/
using FruitsLibrary for uint8;
struct Trait {
string traitName;
string traitType;
string traitLayout;
string traitColors;
}
//Mappings
mapping(string => bool) hashToMinted;
mapping(uint256 => string) internal tokenIdToHash;
mapping(bytes => Trait[]) public traitTypes;
uint32 currentMappingVersion;
//uint256s
uint256 MAX_SUPPLY = 10000;
uint256 MINTS_PER_TIER = 3000;
uint256 SEEDS_NONCE = 0;
// Price
uint256 public price = 50000000000000000; // 0.05 eth
//uint arrays
uint16[][5] TIERS;
//address
address seedsAddress;
address _owner;
constructor() ERC721("Strawberries", "STRBRY") {
_owner = msg.sender;
//Declare all the rarity tiers
//Hat
TIERS[0] = [50, 100, 300, 500, 1250, 1500, 1600, 2200, 2500];
//Eyes
TIERS[1] = [100, 200, 400, 500, 700, 1000, 1100, 1200, 1300, 1400, 2100];
//Mouth
TIERS[2] = [100, 300, 600, 900, 1250, 1750, 2350, 2750];
//Base
TIERS[3] = [50, 100, 250, 400, 500, 600, 600, 800, 1000, 1200, 1500, 3000];
//Background
TIERS[4] = [100, 100, 100, 400, 500, 1300, 1500, 6000];
}
/**
* @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier.
* @param _randinput The input from 0 - 10000 to use for rarity gen.
* @param _rarityTier The tier to use.
*/
function rarityGen(uint256 _randinput, uint8 _rarityTier)
internal
view
returns (string memory)
{
uint16 currentLowerBound = 0;
for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) {
uint16 thisPercentage = TIERS[_rarityTier][i];
if (
_randinput >= currentLowerBound &&
_randinput < currentLowerBound + thisPercentage
){
return i.toString();
}
currentLowerBound = currentLowerBound + thisPercentage;
}
revert();
}
/**
* @dev Generates a 9 digit hash from a tokenId, address, and random number.
* @param _t The token id to be used within the hash.
* @param _a The address to be used within the hash.
* @param _c The custom nonce to be used within the hash.
*/
function hash(
uint256 _t,
address _a,
uint256 _c
) internal returns (string memory) {
require(_c < 10);
// This will generate a 8 character string.
//The last 7 digits are random, the first two are 00, due to the strawberry not being burned.
string memory currentHash = "00";
for (uint8 i = 0; i < 5; i++) {
SEEDS_NONCE++;
uint16 _randinput = uint16(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_t,
_a,
_c,
SEEDS_NONCE
)
)
) % 10000
);
currentHash = string(
abi.encodePacked(currentHash, FruitsLibrary.slice(
string(abi.encodePacked("00",rarityGen(_randinput, i))),2
))
);
}
if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1);
return currentHash;
}
/**
* @dev Returns the current seeds cost of minting.
*/
function currentSeedsCost() public view returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply <= 3000) return 1000000000000000000;
if (_totalSupply > 3000 && _totalSupply <= 4000)
return 1000000000000000000;
if (_totalSupply > 4000 && _totalSupply <= 6000)
return 2000000000000000000;
if (_totalSupply > 6000 && _totalSupply <= 8000)
return 3000000000000000000;
if (_totalSupply > 8000 && _totalSupply <= 10000)
return 4000000000000000000;
revert();
}
/**
* @dev Mint internal, this is to avoid code duplication.
*/
function mintInternal() internal {
uint256 _totalSupply = totalSupply();
require((_totalSupply < MAX_SUPPLY) && (!FruitsLibrary.isContract(msg.sender)));
uint256 thisTokenId = _totalSupply;
tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0);
hashToMinted[tokenIdToHash[thisTokenId]] = true;
_mint(msg.sender, thisTokenId);
}
/**
* @dev Mints new tokens.
*/
function mintStrawberry(uint256 _times) public payable {
require((_times > 0 && _times <= 20) && (msg.value == _times * price) && (totalSupply() < MINTS_PER_TIER), "Check values.");
for(uint256 i=0; i< _times; i++){
mintInternal();
}
}
/**
* @dev Mints new tokens.
*/
function mintStrawberryWithSeeds(uint256 _times) public {
require((_times > 0 && _times <= 20));
//Burn this much seeds
ISeeds(seedsAddress).burnFrom(msg.sender, currentSeedsCost()*_times);
for(uint256 i=0; i< _times; i++){
mintInternal();
}
return;
}
/**
* @dev Burns and mints new.
* @param _tokenId The token to burn.
*/
function burnForMint(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
//Burn token
_transfer(
msg.sender,
0x000000000000000000000000000000000000dEaD,
_tokenId
);
mintInternal();
}
/**
* @dev Hash to SVG function
*/
function hashToSVG(string memory _hash)
public
view
returns (string memory)
{
string memory traitLayout;
string memory traitColors;
uint index = (uint8(bytes(_hash).length)/2)-1;
for (uint8 i = 0; i < bytes(_hash).length; i+=2) {
uint8 thisTraitIndex = FruitsLibrary.parseInt(
FruitsLibrary.substring(_hash, index*2, (index*2) + 2)
);
Trait storage trait = traitTypes[abi.encodePacked(currentMappingVersion, index)][thisTraitIndex];
traitLayout = string(abi.encodePacked(traitLayout,trait.traitLayout));
traitColors = string(abi.encodePacked(traitColors,trait.traitColors));
if(index > 0){
index--;
}
}
return string(
abi.encodePacked(
'<svg style="shape-rendering: crispedges;" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 32 32"> ',
traitLayout,
"<style>rect{width:1px;height:1px;}",
traitColors,
"</style></svg>"
)
);
}
/**
* @dev Hash to metadata function
*/
function hashToMetadata(string memory _hash)
public
view
returns (string memory)
{
string memory metadataString;
uint index = 0;
for (uint8 i = 0; i < bytes(_hash).length; i+=2) {
uint8 thisTraitIndex = FruitsLibrary.parseInt(
FruitsLibrary.substring(_hash, i, i + 2)
);
Trait storage trait = traitTypes[abi.encodePacked(currentMappingVersion, index)][thisTraitIndex];
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
trait.traitType,
'","value":"',
trait.traitName,
'"}'
)
);
if (index != 5)
metadataString = string(abi.encodePacked(metadataString, ","));
index++;
}
return string(abi.encodePacked("[", metadataString, "]"));
}
/**
* @dev Returns the SVG and metadata for a token Id
* @param _tokenId The tokenId to return the SVG and metadata for.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId));
string memory tokenHash = _tokenIdToHash(_tokenId);
return
string(
abi.encodePacked(
"data:application/json;base64,",
FruitsLibrary.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Strawberries #',
FruitsLibrary.toString(_tokenId),
'", "description": "A collection of 10,000 unique strawberries. All the metadata and images are generated and stored on-chain. No IPFS, no API. Just the blockchain.", "image": "data:image/svg+xml;base64,',
FruitsLibrary.encode(
bytes(hashToSVG(tokenHash))
),
'","attributes":',
hashToMetadata(tokenHash),
"}"
)
)
)
)
)
);
}
/**
* @dev Returns a hash for a given tokenId
* @param _tokenId The tokenId to return the hash for.
*/
function _tokenIdToHash(uint256 _tokenId)
public
view
returns (string memory)
{
string memory tokenHash = tokenIdToHash[_tokenId];
//If this is a burned token, override the previous hash
if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) {
tokenHash = string(
abi.encodePacked(
"01",
FruitsLibrary.substring(tokenHash, 2, 12)
)
);
}
return tokenHash;
}
/**
* @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs.
* @param _wallet The wallet to get the tokens of.
*/
function walletOfOwner(address _wallet)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_wallet);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_wallet, i);
}
return tokensId;
}
function getTraits(uint256 _traitTypeIndex) internal returns(Trait[] storage) {
return traitTypes[abi.encodePacked(currentMappingVersion, _traitTypeIndex)];
}
/*function setTraits(uint256 _traitTypeIndex, Trait[] memory _traits) internal {
traitTypes[abi.encodePacked(currentMappingVersion, _traitTypeIndex)] = _traits;
}*/
function clearTraits() external onlyOwner {
currentMappingVersion++;
}
/**
* @dev Recover gas for deleted traits
* @param _version The version of traits to delete
* @param _traitTypeIndex The trait type index
*/
function recoverGas(uint32 _version, uint256 _traitTypeIndex) external onlyOwner {
require(_version < currentMappingVersion);
delete(traitTypes[abi.encodePacked(_version, _traitTypeIndex)]);
}
/**
* @dev Add trait types
* @param _traitTypeIndex The trait type index
* @param traits to add
*/
function addTraitTypes(uint256 _traitTypeIndex, Trait[] memory traits)
public
onlyOwner
{
for(uint i = 0; i < traits.length; i++){
getTraits(_traitTypeIndex).push(
Trait(
traits[i].traitName,
traits[i].traitType,
traits[i].traitLayout,
traits[i].traitColors
)
);
}
return;
}
/**
* @dev Add to a trait type
* @param _traitTypeIndex The trait type index
* @param _traitIndex The trait index
* @param traitLayout to add
*/
function addTraitLayoutChunk(uint256 _traitTypeIndex, uint256 _traitIndex, string memory traitLayout)
public
onlyOwner
{
Trait storage oldTrait = getTraits(_traitTypeIndex)[_traitIndex];
getTraits(_traitTypeIndex)[_traitIndex] = Trait(
oldTrait.traitName,
oldTrait.traitType,
string(abi.encodePacked(oldTrait.traitLayout,traitLayout)),
oldTrait.traitColors
);
return;
}
/**
* @dev Sets the seeds ERC20 address
* @param _seedsAddress The seed address
*/
function setSeedsAddress(address _seedsAddress) public onlyOwner {
seedsAddress = _seedsAddress;
}
/**
* @dev Withdraws balance
*/
function withdraw() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
function contractURI() public view returns (string memory) {
return "https://www.thefruitnft.com/strawberry.json";
}
/**
* @dev Modifier to only allow owner to call functions
*/
modifier onlyOwner() {
require(_owner == msg.sender);
_;
}
}
// 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();
}
}
// contracts/ISeed.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ISeeds is IERC20 {
function burnFrom(address account, uint256 amount) external;
function balanceOf(address _fruitAddress, address staker) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
library FruitsLibrary {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function subbyte(
bytes memory strBytes,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
function slice(
string memory str,
uint startIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
return substring(str,strBytes.length-startIndex,strBytes.length);
}
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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/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;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
/**
* @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);
}
|
Burns and mints new. _tokenId The token to burn./Burn token
|
function burnForMint(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
_transfer(
msg.sender,
0x000000000000000000000000000000000000dEaD,
_tokenId
);
mintInternal();
}
| 14,693,943 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface IUnit {
function balanceOf(address _address) external view returns (uint256);
function stake(address _address) external;
function unstake(address _address) external;
function getStakingStatus(address _address) external view returns (bool);
function stakingInformation() external view returns (address, bool);
}
interface genericBalanceOf {
function balanceOf(address _address) external view returns (uint256);
}
error CallerIsSmartContract();
error CallerNotOwner();
error CallerNotApprovedUnit();
error NewOwnerZeroAddress();
contract MythicalDreamlandPreSeason {
struct _stakeableUnit {
IUnit stakeableContract;
uint256 dailyYield;
uint256 baseYield;
}
struct _stakerData {
uint128 accumulatedRewards;
uint64 lastClaimTimestamp;
uint64 stakedUnlockTimestamp;
}
struct _seasonData {
bool active;
uint256 startTimestamp;
uint256 endTimestamp;
}
address internal _owner;
genericBalanceOf public INHIB;
genericBalanceOf public LORD;
uint256 private immutable etherConversion = 1000000000000000000;
uint256 public totalStakeableUnits;
uint256 public lordBonus = 20;
uint256 public inhibitorBonus = 10;
uint256 public lockedBonus = 50;
uint256 public optionalLockPeriod = 30;
_seasonData public seasonData;
mapping (address => bool) private _approvedUnits;
mapping (address => uint256) private _stakeableUnitsLocations;
mapping (uint256 => _stakeableUnit) private stakeableUnits;
mapping (address => _stakerData) private stakerData;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(address _inhibAddress) {
_transferOwnership(_msgSender());
setInhibitor(_inhibAddress);
}
function _msgSender() internal view returns (address) {
return msg.sender;
}
modifier callerIsUser() {
if (tx.origin != _msgSender() || _msgSender().code.length != 0) revert CallerIsSmartContract();
_;
}
modifier onlyOwner() {
if (owner() != _msgSender()) revert CallerNotOwner();
_;
}
modifier onlyApprovedUnit() {
if (!_approvedUnits[_msgSender()]) revert CallerNotApprovedUnit();
_;
}
/**
* @dev Returns the current timestamp rewards are calculated against.
*/
function getTimestamp() public view returns (uint256) {
uint256 currentTimeStamp = block.timestamp;
if (seasonData.endTimestamp == 0) return currentTimeStamp;
return (currentTimeStamp > seasonData.endTimestamp ? seasonData.endTimestamp : currentTimeStamp);
}
/**
* @dev Stakes the `caller` tokens for `_stakingContract`. If the user elects to opt into time lock, tokens will be locked for 30 days.
* Requirements:
*
* - The season must be active.
* - The `caller` must own an Inhibitor.
* - The `_stakingContract` must be an approved unit.
* - the tokens of `caller` must currently be unstaked.
*/
function stakeUnits(address _stakingContract, bool _optIntoLock) public callerIsUser {
require(seasonData.active, "SeasonHasEnded");
require(INHIB.balanceOf(_msgSender()) > 0, "NoInhibitorOwned");
uint256 location = _stakeableUnitsLocations[_stakingContract];
require(location != 0, "UnknownStakeableUnit");
if (getUserIsStaked(_msgSender())) {
aggregateRewards(_msgSender());
} else {
stakerData[_msgSender()].lastClaimTimestamp = uint64(block.timestamp);
}
if (_optIntoLock) {
stakerData[_msgSender()].stakedUnlockTimestamp = uint64(block.timestamp + (optionalLockPeriod * 1 days));
}
if (!stakeableUnits[location].stakeableContract.getStakingStatus(_msgSender()) && stakeableUnits[location].stakeableContract.balanceOf(_msgSender()) > 0){
stakeableUnits[location].stakeableContract.stake(_msgSender());
} else {
revert("NoUnitsToStake");
}
}
/**
* @dev Unstakes the `caller` tokens for `_stakingContract`.
* Requirements:
*
* - The tokens of `caller` must not currently be optionally locked.
* - The `_stakingContract` must be an approved unit.
* - the tokens of `caller` must currently be staked.
*/
function unstakeUnits(address _stakingContract) public callerIsUser {
uint256 location = _stakeableUnitsLocations[_stakingContract];
require(location != 0, "UnknownStakeableUnit");
require(stakerData[_msgSender()].stakedUnlockTimestamp < block.timestamp, "TimeLockActive");
aggregateRewards(_msgSender());
if (stakeableUnits[location].stakeableContract.getStakingStatus(_msgSender())){
stakeableUnits[location].stakeableContract.unstake(_msgSender());
} else {
revert("NoUnitsToUnstake");
}
}
/**
* @dev Locks in rewards of `_address` for staking.
* Requirements:
*
* - The `caller` must either be `_address` or an approved unit itself.
*/
function aggregateRewards(address _address) public {
require (_approvedUnits[_msgSender()] || _address == _msgSender(), "CallerLacksPermissions");
uint256 rewards = getPendingRewards(_address);
stakerData[_address].lastClaimTimestamp = uint64(block.timestamp);
stakerData[_address].accumulatedRewards += uint128(rewards);
}
/**
* @dev Returns the current total rewards of `_address` from staking.
*/
function getAccumulatedRewards(address _address) public view returns (uint256) {
unchecked {
return getPendingRewards(_address) + stakerData[_address].accumulatedRewards;
}
}
/**
* @dev Returns the current pending rewards of `_address` from staking.
*/
function getPendingRewards(address _address) public view returns (uint256) {
uint256 units = totalStakeableUnits;
if (units == 0) return 0;
uint256 rewards;
unchecked {
for (uint256 i = 1; i <= units; i++){
if (stakeableUnits[i].stakeableContract.getStakingStatus(_address)){
rewards += stakeableUnits[i].stakeableContract.balanceOf(_address) * stakeableUnits[i].baseYield;
}
}
return rewards * getTimeSinceClaimed(_address) * getStakingMultiplier(_address) / 100;
}
}
/**
* @dev Returns the time in seconds it has been since `_address` has last locked in rewards from staking.
*/
function getTimeSinceClaimed(address _address) public view returns (uint256) {
if (stakerData[_address].lastClaimTimestamp == 0) return getTimestamp() - seasonData.startTimestamp;
return stakerData[_address].lastClaimTimestamp > getTimestamp() ? 0 : getTimestamp() - stakerData[_address].lastClaimTimestamp;
}
/**
* @dev Returns the total staking multiplier of `_address`.
*/
function getStakingMultiplier(address _address) public view returns (uint256) {
return 100 + getInhibitorMultiplier(_address) + getLockedMultiplier(_address) + getLordMultiplier(_address);
}
/**
* @dev Returns the Inhibitor staking multiplier of `_address`.
*/
function getInhibitorMultiplier(address _address) public view returns (uint256) {
uint256 inhibBonus = INHIB.balanceOf(_address) * inhibitorBonus;
return inhibBonus > 100 ? 100 : inhibBonus;
}
/**
* @dev Returns the optional lock staking multiplier of `_address`.
*/
function getLockedMultiplier(address _address) public view returns (uint256) {
return stakerData[_address].stakedUnlockTimestamp > 0 ? lockedBonus : 0;
}
/**
* @dev Returns the Lord staking multiplier of `_address`.
*/
function getLordMultiplier(address _address) public view returns (uint256) {
if (address(LORD) == address(0)) return 0;
return LORD.balanceOf(_address) > 0 ? lordBonus : 0;
}
/**
* @dev Returns the current `_stakingContract` unit balance of `_address`.
*/
function getUserUnitBalance(address _address, address _stakingContract) public view returns (uint256) {
return stakeableUnits[_stakeableUnitsLocations[_stakingContract]].stakeableContract.balanceOf(_address);
}
/**
* @dev Returns whether `_address` is staked overall or not.
*/
function getUserIsStaked(address _address) public view returns (bool) {
uint256 units = totalStakeableUnits;
if (units == 0) return false;
for (uint256 i = 1; i <= units; i++){
if (stakeableUnits[i].stakeableContract.getStakingStatus(_address)){
return true;
}
}
return false;
}
/**
* @dev Returns whether `_address` has `_stakingContract` units staked or not.
*/
function getUserStakingStatus(address _address, address _stakingContract) public view returns (bool) {
return stakeableUnits[_stakeableUnitsLocations[_stakingContract]].stakeableContract.getStakingStatus(_address);
}
/**
* @dev Returns the daily token yield of `_address`.
* - Note: This is returned in wei which is the tiniest unit so to see the daily yield in whole tokens divide by 1000000000000000000.
*/
function getUserDailyYield(address _address) public view returns (uint256) {
uint256 units = totalStakeableUnits;
if (units == 0) return 0;
uint256 rewards;
for (uint256 i = 1; i <= units; i++){
if (stakeableUnits[i].stakeableContract.getStakingStatus(_address)){
rewards += stakeableUnits[i].stakeableContract.balanceOf(_address) * stakeableUnits[i].dailyYield;
}
}
return rewards * getStakingMultiplier(_address) / 100;
}
/**
* @dev Updates the yield of `_stakingContract`, only the smart contract owner can call this.
*/
function updateUnitYield(address _stakingContract, uint256 _newYield) public onlyOwner {
uint256 location = _stakeableUnitsLocations[_stakingContract];
require(location != 0, "UnknownStakeableUnit");
stakeableUnits[location].dailyYield = _newYield * etherConversion;
stakeableUnits[location].baseYield = stakeableUnits[location].dailyYield / 86400;
}
/**
* @dev Returns whether `_address` will lock in rewards on receiving a new staked token. Must have been > 1 hour since last claim.
*/
function needsRewardsUpdate(address _address) public view returns (bool) {
return 3600 < getTimeSinceClaimed(_address);
}
/**
* @dev Adds `_unitAddress` as a stakeable unit, only the smart contract owner can call this.
*/
function addApprovedUnit(address _unitAddress) public onlyOwner {
_approvedUnits[_unitAddress] = true;
}
/**
* @dev Removes `_unitAddress` as a stakeable unit, only the smart contract owner can call this.
*/
function removeApprovedUnit(address _unitAddress) public onlyOwner {
delete _approvedUnits[_unitAddress];
}
/**
* @dev Start staking for an approved unit with the daily yield of `_dailyYield`, only approved units can call this.
*/
function startSeason(uint256 _dailyYield) public onlyApprovedUnit {
uint256 newUnit = ++totalStakeableUnits;
_stakeableUnitsLocations[_msgSender()] = newUnit;
stakeableUnits[newUnit].stakeableContract = IUnit(_msgSender());
stakeableUnits[newUnit].dailyYield = _dailyYield * etherConversion;
stakeableUnits[newUnit].baseYield = stakeableUnits[newUnit].dailyYield / 86400;
if (!seasonData.active){
seasonData.active = true;
seasonData.startTimestamp = block.timestamp;
}
}
/**
* @dev Ends staking for all approved units, only approved units can call this.
*/
function endSeason() public onlyApprovedUnit {
seasonData.endTimestamp = block.timestamp;
delete seasonData.active;
}
/**
* @dev Updates the Inhibitor smart contract address to `_address`, only the smart contract owner can call this.
*/
function setInhibitor(address _address) public onlyOwner {
INHIB = genericBalanceOf(_address);
}
/**
* @dev Updates the Lord smart contract address to `_address`, only the smart contract owner can call this.
*/
function setLord(address _address) public onlyOwner {
LORD = genericBalanceOf(_address);
}
/**
* @dev Returns the current smart contract owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns information about the current Staking Season.
* - In the format: Whether Staking is active or not, what time staking started, what time staking ended (0 = has not ended).
*/
function getSeasonData() public view returns (_seasonData memory) {
return seasonData;
}
/**
* @dev Returns information about `_address` approved unit.
* - In the format: Contract Address, Tokens generated per day, tokens generated per second.
* - If zeros are returns, `_address` is not an approved unit.
*/
function getUnitDataByAddress(address _address) public view returns (_stakeableUnit memory) {
return stakeableUnits[_stakeableUnitsLocations[_address]];
}
/**
* @dev Returns information about the number `_location` approved unit.
* - In the format: Contract Address, Tokens generated per day, tokens generated per second.
* - If zeros are returns, that unit location does not exist.
*/
function getUnitDataByLocation(uint256 _location) public view returns (_stakeableUnit memory) {
return stakeableUnits[_location];
}
/**
* @dev Returns information about `_address`'s staking data.
* - In the format: Total Accumulated rewards in Wei, Timestamp since last token claim, timestamp tokens are unstakeable (0 = unlocked).
* - If zeros are returns, `_address` has no data.
*/
function getAddressData(address _address) public view returns (_stakerData memory) {
return stakerData[_address];
}
/**
* @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 {
_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 onlyOwner {
if (newOwner == address(0)) revert NewOwnerZeroAddress();
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
Ends staking for all approved units, only approved units can call this./
|
function endSeason() public onlyApprovedUnit {
seasonData.endTimestamp = block.timestamp;
delete seasonData.active;
}
| 14,326,283 |
pragma solidity 0.5.9;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./thirdparty/BancorPower.sol";
/**
* @title Equation
*
* @dev Equation library abstracts the representation of mathematics equation.
* As of current, an equation is basically an expression tree of constants,
* one variable (X), and operators.
*/
library Equation {
using SafeMath for uint256;
/**
* @dev An expression tree is encoded as a set of nodes, with root node having
* index zero. Each node consists of 3 values:
* 1. opcode: the expression that the node represents. See table below.
* +--------+----------------------------------------+------+------------+
* | Opcode | Description | i.e. | # children |
* +--------+----------------------------------------+------+------------+
* | 00 | Integer Constant | c | 0 |
* | 01 | Variable | X | 0 |
* | 02 | Arithmetic Square Root | √ | 1 |
* | 03 | Boolean Not Condition | ! | 1 |
* | 04 | Arithmetic Addition | + | 2 |
* | 05 | Arithmetic Subtraction | - | 2 |
* | 06 | Arithmetic Multiplication | * | 2 |
* | 07 | Arithmetic Division | / | 2 |
* | 08 | Arithmetic Exponentiation | ** | 2 |
* | 09 | Arithmetic Equal Comparison | == | 2 |
* | 10 | Arithmetic Non-Equal Comparison | != | 2 |
* | 11 | Arithmetic Less-Than Comparison | < | 2 |
* | 12 | Arithmetic Greater-Than Comparison | > | 2 |
* | 13 | Arithmetic Non-Greater-Than Comparison | <= | 2 |
* | 14 | Arithmetic Non-Less-Than Comparison | >= | 2 |
* | 15 | Boolean And Condition | && | 2 |
* | 16 | Boolean Or Condition | || | 2 |
* | 17 | Ternary Operation | ?: | 3 |
* | 18 | Bancor's power* (see below) | | 4 |
* +--------+----------------------------------------+------+------------+
* 2. children: the list of node indices of this node's sub-expressions.
* Different opcode nodes will have different number of children.
* 3. value: the value inside the node. Currently this is only relevant for
* Integer Constant (Opcode 00).
*
* An equation's data is a list of nodes. The nodes will link against
* each other using index as pointer. The root node of the expression tree
* is the first node in the list
*
* (*) Using BancorFomula, the opcode computes exponential of fractional
* numbers. The opcode takes 4 children (c,baseN,baseD,expV), and computes
* (c * ((baseN / baseD) ^ (expV / 1e6))). See implementation for the limitation
* of the each value's domain. The end result must be in uint256 range.
*/
struct Data {
uint256 opcode;
uint256[] constants;
uint8 equationLength;
}
uint8 constant OPCODE_CONST = 0;
uint8 constant OPCODE_VAR = 1;
uint8 constant OPCODE_SQRT = 2;
uint8 constant OPCODE_NOT = 3;
uint8 constant OPCODE_ADD = 4;
uint8 constant OPCODE_SUB = 5;
uint8 constant OPCODE_MUL = 6;
uint8 constant OPCODE_DIV = 7;
uint8 constant OPCODE_EXP = 8;
uint8 constant OPCODE_EQ = 9;
uint8 constant OPCODE_NE = 10;
uint8 constant OPCODE_LT = 11;
uint8 constant OPCODE_GT = 12;
uint8 constant OPCODE_LE = 13;
uint8 constant OPCODE_GE = 14;
uint8 constant OPCODE_AND = 15;
uint8 constant OPCODE_OR = 16;
uint8 constant OPCODE_IF = 17;
uint8 constant OPCODE_BANCOR_POWER = 18;
uint8 constant OPCODE_INVALID = 19;
function init(Data storage self, uint256[] memory _expressions) internal {
assert(self.equationLength == 0);
require(_expressions.length < 32); // For fitting in 1 uint256 opcodes
uint256 nextConstant = 0;
for (uint8 idx = 0; idx < _expressions.length; ++idx) {
// Get the next opcode. Obviously it must be within the opcode range.
uint256 opcode = _expressions[idx];
require(opcode < OPCODE_INVALID);
self.opcode = self.opcode | (opcode << ((31 - idx) * 8));
// Get the node's value. Only applicable on Integer Constant case.
if (opcode == OPCODE_CONST) {
self.constants.push(_expressions[++idx]);
self.opcode = self.opcode | (nextConstant << ((31 - idx)*8));
nextConstant++;
}
}
self.equationLength = uint8(_expressions.length);
}
/**
* @dev Calculate the Y position from the X position for this equation.
*/
function calculate(Data storage self, uint256 xValue)
internal
view
returns (uint256)
{
(uint8 end, uint256 val) = solveMath(self.opcode, self.constants, 0, xValue);
require(end == self.equationLength - 1);
return val;
}
/**
* @dev Return the number of children the given opcode node has.
*/
function getChildrenCount(uint8 opcode) private pure returns (uint8) {
if (opcode <= OPCODE_VAR) {
return 0;
} else if (opcode <= OPCODE_NOT) {
return 1;
} else if (opcode <= OPCODE_OR) {
return 2;
} else if (opcode <= OPCODE_IF) {
return 3;
} else if (opcode <= OPCODE_BANCOR_POWER) {
return 4;
} else {
assert(false);
}
}
function getOpcodeAt(uint256 opcodes, uint8 index)
private
pure
returns (uint8)
{
require(index < 32);
return uint8((opcodes >> ((31-index) * 8)) & 255);
}
function dryRun(uint256 opcodes, uint256[] memory constants, uint8 startIndex)
private
view
returns (uint8)
{
require(startIndex < 32);
uint8 opcode = getOpcodeAt(opcodes, startIndex);
if (opcode == OPCODE_CONST)
return startIndex + 1;
uint8 childrenCount = getChildrenCount(opcode);
uint8 lastIndex = startIndex;
for (uint8 idx = 0; idx < childrenCount; ++idx) {
lastIndex = dryRun(opcodes, constants, lastIndex + 1);
}
return lastIndex;
}
/**
* @dev Calculate the arithmetic value of this sub-expression at the given
* X position.
*/
function solveMath(uint256 opcodes, uint256[] memory constants, uint8 startIndex, uint256 xValue)
private
view
returns (uint8, uint256)
{
require(startIndex < 32);
uint8 opcode = getOpcodeAt(opcodes, startIndex);
if (opcode == OPCODE_CONST) {
return (startIndex + 1, constants[getOpcodeAt(opcodes, startIndex + 1)]);
} else if (opcode == OPCODE_VAR) {
return (startIndex, xValue);
} else if (opcode == OPCODE_SQRT) {
(uint8 endIndex, uint256 childValue) = solveMath(opcodes, constants, startIndex + 1, xValue);
uint256 temp = childValue.add(1).div(2);
uint256 result = childValue;
while (temp < result) {
result = temp;
temp = childValue.div(temp).add(temp).div(2);
}
return (endIndex, result);
} else if (opcode >= OPCODE_ADD && opcode <= OPCODE_EXP) {
(uint8 leftEndIndex, uint256 leftValue) = solveMath(opcodes, constants, startIndex + 1, xValue);
(uint8 endIndex, uint256 rightValue) = solveMath(opcodes, constants, leftEndIndex + 1, xValue);
if (opcode == OPCODE_ADD) {
return (endIndex, leftValue.add(rightValue));
} else if (opcode == OPCODE_SUB) {
return (endIndex, leftValue.sub(rightValue));
} else if (opcode == OPCODE_MUL) {
return (endIndex, leftValue.mul(rightValue));
} else if (opcode == OPCODE_DIV) {
return (endIndex, leftValue.div(rightValue));
} else if (opcode == OPCODE_EXP) {
uint256 power = rightValue;
uint256 expResult = 1;
for (uint256 idx = 0; idx < power; ++idx) {
expResult = expResult.mul(leftValue);
}
return (endIndex, expResult);
}
} else if (opcode == OPCODE_IF) {
(uint8 condEndIndex, bool condValue) = solveBool(opcodes, constants, startIndex + 1, xValue);
if (condValue) {
(uint8 thenEndIndex, uint256 thenValue) = solveMath(opcodes, constants, condEndIndex + 1, xValue);
return (dryRun(opcodes, constants, thenEndIndex + 1), thenValue);
} else {
uint8 thenEndIndex = dryRun(opcodes, constants, condEndIndex + 1);
return solveMath(opcodes, constants, thenEndIndex + 1, xValue);
}
} else if (opcode == OPCODE_BANCOR_POWER) {
(uint8 multiplerEndIndex, uint256 multipler) = solveMath(opcodes, constants,startIndex + 1, xValue);
(uint8 baseNEndIndex, uint256 baseN) = solveMath(opcodes, constants, multiplerEndIndex + 1, xValue);
(uint8 baseDEndIndex, uint256 baseD) = solveMath(opcodes, constants, baseNEndIndex + 1, xValue);
(uint8 expVEndIndex, uint256 expV) = solveMath(opcodes, constants, baseDEndIndex + 1, xValue);
require(expV < 1 << 32);
(uint256 expResult, uint8 precision) = BancorPower.power(baseN, baseD, uint32(expV), 1e6);
return (expVEndIndex, expResult.mul(multipler) >> precision);
}
require(false);
}
/**
* @dev Calculate the arithmetic value of this sub-expression.
*/
function solveBool(uint256 opcodes, uint256[] memory constants, uint8 startIndex, uint256 xValue)
private
view
returns (uint8, bool)
{
require(startIndex < 32);
uint8 opcode = getOpcodeAt(opcodes, startIndex);
if (opcode == OPCODE_NOT) {
(uint8 endIndex, bool value) = solveBool(opcodes, constants, startIndex + 1, xValue);
return (endIndex, !value);
} else if (opcode >= OPCODE_EQ && opcode <= OPCODE_GE) {
(uint8 leftEndIndex, uint256 leftValue) = solveMath(opcodes, constants, startIndex + 1, xValue);
(uint8 rightEndIndex, uint256 rightValue) = solveMath(opcodes, constants, leftEndIndex + 1, xValue);
if (opcode == OPCODE_EQ) {
return (rightEndIndex, leftValue == rightValue);
} else if (opcode == OPCODE_NE) {
return (rightEndIndex, leftValue != rightValue);
} else if (opcode == OPCODE_LT) {
return (rightEndIndex, leftValue < rightValue);
} else if (opcode == OPCODE_GT) {
return (rightEndIndex, leftValue > rightValue);
} else if (opcode == OPCODE_LE) {
return (rightEndIndex, leftValue <= rightValue);
} else if (opcode == OPCODE_GE) {
return (rightEndIndex, leftValue >= rightValue);
}
} else if (opcode >= OPCODE_AND && opcode <= OPCODE_OR) {
(uint8 leftEndIndex, bool leftBoolValue) = solveBool(opcodes, constants, startIndex + 1, xValue);
if (opcode == OPCODE_AND) {
if (leftBoolValue)
return solveBool(opcodes, constants, leftEndIndex + 1, xValue);
else
return (dryRun(opcodes, constants, leftEndIndex + 1), false);
} else if (opcode == OPCODE_OR) {
if (leftBoolValue)
return (dryRun(opcodes, constants, leftEndIndex + 1), true);
else
return solveBool(opcodes, constants, leftEndIndex + 1, xValue);
}
} else if (opcode == OPCODE_IF) {
(uint8 condEndIndex, bool condValue) = solveBool(opcodes, constants, startIndex + 1, xValue);
if (condValue) {
(uint8 thenEndIndex, bool thenValue) = solveBool(opcodes, constants, condEndIndex + 1, xValue);
return (dryRun(opcodes, constants, thenEndIndex + 1), thenValue);
} else {
uint8 thenEndIndex = dryRun(opcodes, constants, condEndIndex + 1);
return solveBool(opcodes, constants, thenEndIndex + 1, xValue);
}
}
require(false);
}
}
|
Calculate the arithmetic value of this sub-expression./
|
function solveBool(uint256 opcodes, uint256[] memory constants, uint8 startIndex, uint256 xValue)
private
view
returns (uint8, bool)
{
require(startIndex < 32);
uint8 opcode = getOpcodeAt(opcodes, startIndex);
if (opcode == OPCODE_NOT) {
(uint8 endIndex, bool value) = solveBool(opcodes, constants, startIndex + 1, xValue);
return (endIndex, !value);
(uint8 leftEndIndex, uint256 leftValue) = solveMath(opcodes, constants, startIndex + 1, xValue);
(uint8 rightEndIndex, uint256 rightValue) = solveMath(opcodes, constants, leftEndIndex + 1, xValue);
if (opcode == OPCODE_EQ) {
return (rightEndIndex, leftValue == rightValue);
return (rightEndIndex, leftValue != rightValue);
return (rightEndIndex, leftValue < rightValue);
return (rightEndIndex, leftValue > rightValue);
return (rightEndIndex, leftValue <= rightValue);
return (rightEndIndex, leftValue >= rightValue);
}
(uint8 leftEndIndex, bool leftBoolValue) = solveBool(opcodes, constants, startIndex + 1, xValue);
if (opcode == OPCODE_AND) {
if (leftBoolValue)
return solveBool(opcodes, constants, leftEndIndex + 1, xValue);
else
return (dryRun(opcodes, constants, leftEndIndex + 1), false);
if (leftBoolValue)
return (dryRun(opcodes, constants, leftEndIndex + 1), true);
else
return solveBool(opcodes, constants, leftEndIndex + 1, xValue);
}
(uint8 condEndIndex, bool condValue) = solveBool(opcodes, constants, startIndex + 1, xValue);
if (condValue) {
(uint8 thenEndIndex, bool thenValue) = solveBool(opcodes, constants, condEndIndex + 1, xValue);
return (dryRun(opcodes, constants, thenEndIndex + 1), thenValue);
uint8 thenEndIndex = dryRun(opcodes, constants, condEndIndex + 1);
return solveBool(opcodes, constants, thenEndIndex + 1, xValue);
}
}
require(false);
}
| 12,651,077 |
./partial_match/1/0x9cE40fb807eaF4aB3712c7D8797eE8107B36C46e/sources/FckAirdrop.sol
|
Addition to StandardToken methods. Decrease the amount of tokens that an owner allowed to a spender and execute a call with the sent data. 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 _spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by. _data ABI-encoded contract call to call `_spender` address./
|
function decreaseApprovalAndCall(address _spender, uint _subtractedValue, bytes _data) public payable returns (bool) {
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
require(_spender.call.value(msg.value)(_data));
return true;
}
| 4,259,930 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract 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;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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) {
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 uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
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) {
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 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) {
// 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) require(allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @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 returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Transmutable {
function transmute(address to, uint256 value) returns (bool, uint256);
event Transmuted(address indexed who, address baseContract, address transmutedContract, uint256 sourceQuantity, uint256 destQuantity);
}
// Contracts that can be transmuted to should implement this
contract TransmutableInterface {
function transmuted(uint256 _value) returns (bool, uint256);
}
contract ERC20Mineable is StandardToken, ReentrancyGuard {
uint256 public constant divisible_units = 10000000;
uint256 public constant decimals = 8;
uint256 public constant initial_reward = 100;
/** totalSupply in StandardToken refers to currently available supply
* maximumSupply refers to the cap on mining.
* When mining is finished totalSupply == maximumSupply
*/
uint256 public maximumSupply;
// Current mining difficulty in Wei
uint256 public currentDifficultyWei;
// Minimum difficulty
uint256 public minimumDifficultyThresholdWei;
/** Block creation rate as number of Ethereum blocks per mining cycle
* 10 minutes at 12 seconds a block would be an internal block
* generated every 50 Ethereum blocks
*/
uint256 public blockCreationRate;
/* difficultyAdjustmentPeriod should be every two weeks, or
* 2016 internal blocks.
*/
uint256 public difficultyAdjustmentPeriod;
/* When was the last time we did a difficulty adjustment.
* In case mining ceases for indeterminate duration
*/
uint256 public lastDifficultyAdjustmentEthereumBlock;
// Scale multiplier limit for difficulty adjustment
uint256 public constant difficultyScaleMultiplierLimit = 4;
// Total blocks mined helps us calculate the current reward
uint256 public totalBlocksMined;
// Reward adjustment period in Bitcoineum native blocks
uint256 public rewardAdjustmentPeriod;
// Total amount of Wei put into mining during current period
uint256 public totalWeiCommitted;
// Total amount of Wei expected for this mining period
uint256 public totalWeiExpected;
// Where to burn Ether
address public burnAddress;
/** Each block is created on a mining attempt if
* it does not already exist.
* this keeps track of the target difficulty at the time of creation
*/
struct InternalBlock {
uint256 targetDifficultyWei;
uint256 blockNumber;
uint256 totalMiningWei;
uint256 totalMiningAttempts;
uint256 currentAttemptOffset;
bool payed;
address payee;
bool isCreated;
}
/** Mining attempts are given a projected offset to minimize
* keyspace overlap to increase fairness by reducing the redemption
* race condition
* This does not remove the possibility that two or more miners will
* be competing for the same award, especially if subsequent increases in
* wei from a single miner increase overlap
*/
struct MiningAttempt {
uint256 projectedOffset;
uint256 value;
bool isCreated;
}
// Each guess gets assigned to a block
mapping (uint256 => InternalBlock) public blockData;
mapping (uint256 => mapping (address => MiningAttempt)) public miningAttempts;
// Utility related
function resolve_block_hash(uint256 _blockNum) public constant returns (bytes32) {
return block.blockhash(_blockNum);
}
function current_external_block() public constant returns (uint256) {
return block.number;
}
function external_to_internal_block_number(uint256 _externalBlockNum) public constant returns (uint256) {
// blockCreationRate is > 0
return _externalBlockNum / blockCreationRate;
}
// For the test harness verification
function get_internal_block_number() public constant returns (uint256) {
return external_to_internal_block_number(current_external_block());
}
// Initial state related
/** Dapps need to grab the initial state of the contract
* in order to properly initialize mining or tracking
* this is a single atomic function for getting state
* rather than scattering it across multiple public calls
* also returns the current blocks parameters
* or default params if it hasn't been created yet
* This is only called externally
*/
function getContractState() external constant
returns (uint256, // currentDifficultyWei
uint256, // minimumDifficultyThresholdWei
uint256, // blockNumber
uint256, // blockCreationRate
uint256, // difficultyAdjustmentPeriod
uint256, // rewardAdjustmentPeriod
uint256, // lastDifficultyAdustmentEthereumBlock
uint256, // totalBlocksMined
uint256, // totalWeiCommitted
uint256, // totalWeiExpected
uint256, // b.targetDifficultyWei
uint256, // b.totalMiningWei
uint256 // b.currentAttemptOffset
) {
InternalBlock memory b;
uint256 _blockNumber = external_to_internal_block_number(current_external_block());
if (!blockData[_blockNumber].isCreated) {
b = InternalBlock(
{targetDifficultyWei: currentDifficultyWei,
blockNumber: _blockNumber,
totalMiningWei: 0,
totalMiningAttempts: 0,
currentAttemptOffset: 0,
payed: false,
payee: 0,
isCreated: true
});
} else {
b = blockData[_blockNumber];
}
return (currentDifficultyWei,
minimumDifficultyThresholdWei,
_blockNumber,
blockCreationRate,
difficultyAdjustmentPeriod,
rewardAdjustmentPeriod,
lastDifficultyAdjustmentEthereumBlock,
totalBlocksMined,
totalWeiCommitted,
totalWeiExpected,
b.targetDifficultyWei,
b.totalMiningWei,
b.currentAttemptOffset);
}
function getBlockData(uint256 _blockNum) public constant returns (uint256, uint256, uint256, uint256, uint256, bool, address, bool) {
InternalBlock memory iBlock = blockData[_blockNum];
return (iBlock.targetDifficultyWei,
iBlock.blockNumber,
iBlock.totalMiningWei,
iBlock.totalMiningAttempts,
iBlock.currentAttemptOffset,
iBlock.payed,
iBlock.payee,
iBlock.isCreated);
}
function getMiningAttempt(uint256 _blockNum, address _who) public constant returns (uint256, uint256, bool) {
if (miningAttempts[_blockNum][_who].isCreated) {
return (miningAttempts[_blockNum][_who].projectedOffset,
miningAttempts[_blockNum][_who].value,
miningAttempts[_blockNum][_who].isCreated);
} else {
return (0, 0, false);
}
}
// Mining Related
modifier blockCreated(uint256 _blockNum) {
require(blockData[_blockNum].isCreated);
_;
}
modifier blockRedeemed(uint256 _blockNum) {
require(_blockNum != current_external_block());
/* Should capture if the blockdata is payed
* or if it does not exist in the blockData mapping
*/
require(blockData[_blockNum].isCreated);
require(!blockData[_blockNum].payed);
_;
}
modifier initBlock(uint256 _blockNum) {
require(_blockNum != current_external_block());
if (!blockData[_blockNum].isCreated) {
// This is a new block, adjust difficulty
adjust_difficulty();
// Create new block for tracking
blockData[_blockNum] = InternalBlock(
{targetDifficultyWei: currentDifficultyWei,
blockNumber: _blockNum,
totalMiningWei: 0,
totalMiningAttempts: 0,
currentAttemptOffset: 0,
payed: false,
payee: 0,
isCreated: true
});
}
_;
}
modifier isValidAttempt() {
/* If the Ether for this mining attempt is less than minimum
* 0.0000001 % of total difficulty
*/
uint256 minimum_wei = currentDifficultyWei / divisible_units;
require (msg.value >= minimum_wei);
/* Let's bound the value to guard against potential overflow
* i.e max int, or an underflow bug
* This is a single attempt
*/
require(msg.value <= (1000000 ether));
_;
}
modifier alreadyMined(uint256 blockNumber, address sender) {
require(blockNumber != current_external_block());
/* We are only going to allow one mining attempt per block per account
* This prevents stuffing and make it easier for us to track boundaries
*/
// This user already made a mining attempt for this block
require(!checkMiningAttempt(blockNumber, sender));
_;
}
function checkMiningActive() public constant returns (bool) {
return (totalSupply < maximumSupply);
}
modifier isMiningActive() {
require(checkMiningActive());
_;
}
function burn(uint256 value) internal {
/* We don't really care if the burn fails for some
* weird reason.
*/
bool ret = burnAddress.send(value);
/* If we cannot burn this ether, than the contract might
* be under some kind of stack attack.
* Even though it shouldn't matter, let's err on the side of
* caution and throw in case there is some invalid state.
*/
require (ret);
}
event MiningAttemptEvent(
address indexed _from,
uint256 _value,
uint256 indexed _blockNumber,
uint256 _totalMinedWei,
uint256 _targetDifficultyWei
);
event LogEvent(
string _info
);
/**
* @dev Add a mining attempt for the current internal block
* Initialize an empty block if not created
* Invalidate this mining attempt if the block has been paid out
*/
function mine() external payable
nonReentrant
isValidAttempt
isMiningActive
initBlock(external_to_internal_block_number(current_external_block()))
blockRedeemed(external_to_internal_block_number(current_external_block()))
alreadyMined(external_to_internal_block_number(current_external_block()), msg.sender) returns (bool) {
/* Let's immediately adjust the difficulty
* In case an abnormal period of time has elapsed
* nobody has been mining etc.
* Will let us recover the network even if the
* difficulty spikes to some absurd amount
* this should only happen on the first attempt on a block
*/
uint256 internalBlockNum = external_to_internal_block_number(current_external_block());
miningAttempts[internalBlockNum][msg.sender] =
MiningAttempt({projectedOffset: blockData[internalBlockNum].currentAttemptOffset,
value: msg.value,
isCreated: true});
// Increment the mining attempts for this block
blockData[internalBlockNum].totalMiningAttempts += 1;
blockData[internalBlockNum].totalMiningWei += msg.value;
totalWeiCommitted += msg.value;
/* We are trying to stack mining attempts into their relative
* positions in the key space.
*/
blockData[internalBlockNum].currentAttemptOffset += msg.value;
MiningAttemptEvent(msg.sender,
msg.value,
internalBlockNum,
blockData[internalBlockNum].totalMiningWei,
blockData[internalBlockNum].targetDifficultyWei
);
// All mining attempt Ether is burned
burn(msg.value);
return true;
}
// Redemption Related
modifier userMineAttempted(uint256 _blockNum, address _user) {
require(checkMiningAttempt(_blockNum, _user));
_;
}
modifier isBlockMature(uint256 _blockNumber) {
require(_blockNumber != current_external_block());
require(checkBlockMature(_blockNumber, current_external_block()));
require(checkRedemptionWindow(_blockNumber, current_external_block()));
_;
}
// Just in case this block falls outside of the available
// block range, possibly because of a change in network params
modifier isBlockReadable(uint256 _blockNumber) {
InternalBlock memory iBlock = blockData[_blockNumber];
uint256 targetBlockNum = targetBlockNumber(_blockNumber);
require(resolve_block_hash(targetBlockNum) != 0);
_;
}
function calculate_difficulty_attempt(uint256 targetDifficultyWei,
uint256 totalMiningWei,
uint256 value) public constant returns (uint256) {
// The total amount of Wei sent for this mining attempt exceeds the difficulty level
// So the calculation of percentage keyspace should be done on the total wei.
uint256 selectedDifficultyWei = 0;
if (totalMiningWei > targetDifficultyWei) {
selectedDifficultyWei = totalMiningWei;
} else {
selectedDifficultyWei = targetDifficultyWei;
}
/* normalize the value against the entire key space
* Multiply it out because we do not have floating point
* 10000000 is .0000001 % increments
*/
uint256 intermediate = ((value * divisible_units) / selectedDifficultyWei);
uint256 max_int = 0;
// Underflow to maxint
max_int = max_int - 1;
if (intermediate >= divisible_units) {
return max_int;
} else {
return intermediate * (max_int / divisible_units);
}
}
function calculate_range_attempt(uint256 difficulty, uint256 offset) public constant returns (uint256, uint256) {
/* Both the difficulty and offset should be normalized
* against the difficulty scale.
* If they are not we might have an integer overflow
*/
require(offset + difficulty >= offset);
return (offset, offset+difficulty);
}
// Total allocated reward is proportional to burn contribution to limit incentive for
// hash grinding attacks
function calculate_proportional_reward(uint256 _baseReward, uint256 _userContributionWei, uint256 _totalCommittedWei) public constant returns (uint256) {
require(_userContributionWei <= _totalCommittedWei);
require(_userContributionWei > 0);
require(_totalCommittedWei > 0);
uint256 intermediate = ((_userContributionWei * divisible_units) / _totalCommittedWei);
if (intermediate >= divisible_units) {
return _baseReward;
} else {
return intermediate * (_baseReward / divisible_units);
}
}
function calculate_base_mining_reward(uint256 _totalBlocksMined) public constant returns (uint256) {
/* Block rewards starts at initial_reward
* Every 10 minutes
* Block reward decreases by 50% every 210000 blocks
*/
uint256 mined_block_period = 0;
if (_totalBlocksMined < 210000) {
mined_block_period = 210000;
} else {
mined_block_period = _totalBlocksMined;
}
// Again we have to do this iteratively because of floating
// point limitations in solidity.
uint256 total_reward = initial_reward * (10 ** decimals);
uint256 i = 1;
uint256 rewardperiods = mined_block_period / 210000;
if (mined_block_period % 210000 > 0) {
rewardperiods += 1;
}
for (i=1; i < rewardperiods; i++) {
total_reward = total_reward / 2;
}
return total_reward;
}
// Break out the expected wei calculation
// for easy external testing
function calculate_next_expected_wei(uint256 _totalWeiCommitted,
uint256 _totalWeiExpected,
uint256 _minimumDifficultyThresholdWei,
uint256 _difficultyScaleMultiplierLimit) public constant
returns (uint256) {
/* The adjustment window has been fulfilled
* The new difficulty should be bounded by the total wei actually spent
* capped at difficultyScaleMultiplierLimit times
*/
uint256 lowerBound = _totalWeiExpected / _difficultyScaleMultiplierLimit;
uint256 upperBound = _totalWeiExpected * _difficultyScaleMultiplierLimit;
if (_totalWeiCommitted < lowerBound) {
_totalWeiExpected = lowerBound;
} else if (_totalWeiCommitted > upperBound) {
_totalWeiExpected = upperBound;
} else {
_totalWeiExpected = _totalWeiCommitted;
}
/* If difficulty drops too low lets set it to our minimum.
* This may halt coin creation, but obviously does not affect
* token transactions.
*/
if (_totalWeiExpected < _minimumDifficultyThresholdWei) {
_totalWeiExpected = _minimumDifficultyThresholdWei;
}
return _totalWeiExpected;
}
function adjust_difficulty() internal {
/* Total blocks mined might not be increasing if the
* difficulty is too high. So we should instead base the adjustment
* on the progression of the Ethereum network.
* So that the difficulty can increase/deflate regardless of sparse
* mining attempts
*/
if ((current_external_block() - lastDifficultyAdjustmentEthereumBlock) > (difficultyAdjustmentPeriod * blockCreationRate)) {
// Get the new total wei expected via static function
totalWeiExpected = calculate_next_expected_wei(totalWeiCommitted, totalWeiExpected, minimumDifficultyThresholdWei * difficultyAdjustmentPeriod, difficultyScaleMultiplierLimit);
currentDifficultyWei = totalWeiExpected / difficultyAdjustmentPeriod;
// Regardless of difficulty adjustment, let us zero totalWeiCommited
totalWeiCommitted = 0;
// Lets reset the difficulty adjustment block target
lastDifficultyAdjustmentEthereumBlock = current_external_block();
}
}
event BlockClaimedEvent(
address indexed _from,
address indexed _forCreditTo,
uint256 _reward,
uint256 indexed _blockNumber
);
modifier onlyWinner(uint256 _blockNumber) {
require(checkWinning(_blockNumber));
_;
}
// Helper function to avoid stack issues
function calculate_reward(uint256 _totalBlocksMined, address _sender, uint256 _blockNumber) public constant returns (uint256) {
return calculate_proportional_reward(calculate_base_mining_reward(_totalBlocksMined), miningAttempts[_blockNumber][_sender].value, blockData[_blockNumber].totalMiningWei);
}
/**
* @dev Claim the mining reward for a given block
* @param _blockNumber The internal block that the user is trying to claim
* @param forCreditTo When the miner account is different from the account
* where we want to deliver the redeemed Bitcoineum. I.e Hard wallet.
*/
function claim(uint256 _blockNumber, address forCreditTo)
nonReentrant
blockRedeemed(_blockNumber)
isBlockMature(_blockNumber)
isBlockReadable(_blockNumber)
userMineAttempted(_blockNumber, msg.sender)
onlyWinner(_blockNumber)
external returns (bool) {
/* If attempt is valid, invalidate redemption
* Difficulty is adjusted here
* and on bidding, in case bidding stalls out for some
* unusual period of time.
* Do everything, then adjust supply and balance
*/
blockData[_blockNumber].payed = true;
blockData[_blockNumber].payee = msg.sender;
totalBlocksMined = totalBlocksMined + 1;
uint256 proportional_reward = calculate_reward(totalBlocksMined, msg.sender, _blockNumber);
balances[forCreditTo] = balances[forCreditTo].add(proportional_reward);
totalSupply += proportional_reward;
BlockClaimedEvent(msg.sender, forCreditTo,
proportional_reward,
_blockNumber);
// Mining rewards should show up as ERC20 transfer events
// So that ERC20 scanners will see token creation.
Transfer(this, forCreditTo, proportional_reward);
return true;
}
/**
* @dev Claim the mining reward for a given block
* @param _blockNum The internal block that the user is trying to claim
*/
function isBlockRedeemed(uint256 _blockNum) constant public returns (bool) {
if (!blockData[_blockNum].isCreated) {
return false;
} else {
return blockData[_blockNum].payed;
}
}
/**
* @dev Get the target block in the winning equation
* @param _blockNum is the internal block number to get the target block for
*/
function targetBlockNumber(uint256 _blockNum) constant public returns (uint256) {
return ((_blockNum + 1) * blockCreationRate);
}
/**
* @dev Check whether a given block is mature
* @param _blockNum is the internal block number to check
*/
function checkBlockMature(uint256 _blockNum, uint256 _externalblock) constant public returns (bool) {
return (_externalblock >= targetBlockNumber(_blockNum));
}
/**
* @dev Check the redemption window for a given block
* @param _blockNum is the internal block number to check
*/
function checkRedemptionWindow(uint256 _blockNum, uint256 _externalblock) constant public returns (bool) {
uint256 _targetblock = targetBlockNumber(_blockNum);
return _externalblock >= _targetblock && _externalblock < (_targetblock + 256);
}
/**
* @dev Check whether a mining attempt was made by sender for this block
* @param _blockNum is the internal block number to check
*/
function checkMiningAttempt(uint256 _blockNum, address _sender) constant public returns (bool) {
return miningAttempts[_blockNum][_sender].isCreated;
}
/**
* @dev Did the user win a specific block and can claim it?
* @param _blockNum is the internal block number to check
*/
function checkWinning(uint256 _blockNum) constant public returns (bool) {
if (checkMiningAttempt(_blockNum, msg.sender) && checkBlockMature(_blockNum, current_external_block())) {
InternalBlock memory iBlock = blockData[_blockNum];
uint256 targetBlockNum = targetBlockNumber(iBlock.blockNumber);
MiningAttempt memory attempt = miningAttempts[_blockNum][msg.sender];
uint256 difficultyAttempt = calculate_difficulty_attempt(iBlock.targetDifficultyWei, iBlock.totalMiningWei, attempt.value);
uint256 beginRange;
uint256 endRange;
uint256 targetBlockHashInt;
(beginRange, endRange) = calculate_range_attempt(difficultyAttempt,
calculate_difficulty_attempt(iBlock.targetDifficultyWei, iBlock.totalMiningWei, attempt.projectedOffset));
targetBlockHashInt = uint256(keccak256(resolve_block_hash(targetBlockNum)));
// This is the winning condition
if ((beginRange < targetBlockHashInt) && (endRange >= targetBlockHashInt))
{
return true;
}
}
return false;
}
}
contract Bitcoineum is ERC20Mineable, Transmutable {
string public constant name = "Bitcoineum";
string public constant symbol = "BTE";
uint256 public constant decimals = 8;
uint256 public constant INITIAL_SUPPLY = 0;
// 21 Million coins at 8 decimal places
uint256 public constant MAX_SUPPLY = 21000000 * (10**8);
function Bitcoineum() {
totalSupply = INITIAL_SUPPLY;
maximumSupply = MAX_SUPPLY;
// 0.0001 Ether per block
// Difficulty is so low because it doesn't include
// gas prices for execution
currentDifficultyWei = 100 szabo;
minimumDifficultyThresholdWei = 100 szabo;
// Ethereum blocks to internal blocks
// Roughly 10 minute windows
blockCreationRate = 50;
// Adjust difficulty x claimed internal blocks
difficultyAdjustmentPeriod = 2016;
// Reward adjustment
rewardAdjustmentPeriod = 210000;
// This is the effective block counter, since block windows are discontinuous
totalBlocksMined = 0;
totalWeiExpected = difficultyAdjustmentPeriod * currentDifficultyWei;
// Balance of this address can be used to determine total burned value
// not including fees spent.
burnAddress = 0xdeaDDeADDEaDdeaDdEAddEADDEAdDeadDEADDEaD;
lastDifficultyAdjustmentEthereumBlock = block.number;
}
/**
* @dev Bitcoineum can extend proof of burn into convertable units
* that have token specific properties
* @param to is the address of the contract that Bitcoineum is converting into
* @param value is the quantity of Bitcoineum to attempt to convert
*/
function transmute(address to, uint256 value) nonReentrant returns (bool, uint256) {
require(value > 0);
require(balances[msg.sender] >= value);
require(totalSupply >= value);
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply = totalSupply.sub(value);
TransmutableInterface target = TransmutableInterface(to);
bool _result = false;
uint256 _total = 0;
(_result, _total) = target.transmuted(value);
require (_result);
Transmuted(msg.sender, this, to, value, _total);
return (_result, _total);
}
}
|
0.0001 Ether per block Difficulty is so low because it doesn't include gas prices for execution Ethereum blocks to internal blocks Roughly 10 minute windows Adjust difficulty x claimed internal blocks Reward adjustment This is the effective block counter, since block windows are discontinuous Balance of this address can be used to determine total burned value not including fees spent.
|
function Bitcoineum() {
totalSupply = INITIAL_SUPPLY;
maximumSupply = MAX_SUPPLY;
currentDifficultyWei = 100 szabo;
minimumDifficultyThresholdWei = 100 szabo;
blockCreationRate = 50;
difficultyAdjustmentPeriod = 2016;
rewardAdjustmentPeriod = 210000;
totalBlocksMined = 0;
totalWeiExpected = difficultyAdjustmentPeriod * currentDifficultyWei;
burnAddress = 0xdeaDDeADDEaDdeaDdEAddEADDEAdDeadDEADDEaD;
lastDifficultyAdjustmentEthereumBlock = block.number;
}
| 2,478,629 |
./full_match/4/0x11b7d8077083211B3924d0AEF919BeB145D5D282/sources/kali.sol
|
cannot realistically overflow on human timescales
|
function init(
string memory name_,
string memory symbol_,
string memory docs_,
bool paused_,
address[] memory extensions_,
bytes[] memory extensionsData_,
address[] memory voters_,
uint256[] memory shares_,
uint32 votingPeriod_,
uint8[13] memory govSettings_
) public payable nonReentrant virtual {
if (extensions_.length != extensionsData_.length) revert NoArrayParity();
if (votingPeriod != 0) revert Initialized();
if (votingPeriod_ == 0 || votingPeriod_ > 365 days) revert VotingPeriodBounds();
if (govSettings_[0] > 100) revert QuorumMax();
if (govSettings_[1] <= 51 || govSettings_[1] > 100) revert SupermajorityBounds();
KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_);
if (extensions_.length != 0) {
unchecked {
for (uint256 i; i < extensions_.length; i++) {
extensions[extensions_[i]] = true;
if (extensionsData_[i].length != 0) IKaliDAOextension(extensions_[i])
.setExtension(extensionsData_[i]);
}
}
}
docs = docs_;
votingPeriod = votingPeriod_;
quorum = govSettings_[0];
supermajority = govSettings_[1];
proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[3]);
proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[4]);
proposalVoteTypes[ProposalType.PERIOD] = VoteType(govSettings_[5]);
proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[6]);
proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[7]);
proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[8]);
proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[9]);
proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[10]);
proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[11]);
proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[12]);
}
PROPOSAL LOGIC
| 777,942 |
./partial_match/1/0x2336Fdd0F1109C14Fd565cfb1f83D8726736A087/sources/POTTER.sol
|
ERC-20 token interface
|
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);
pragma solidity ^0.8.0;
}
| 16,112,724 |
./full_match/80001/0x79c1E01A9D9E0019d14Bf1Ef80eFA65A916A2B23/sources/project_/contracts/token/Token.sol
|
See {IToken-recoveryAddress}./
|
function recoveryAddress(
address _lostWallet,
address _newWallet,
address _investorOnchainID
) external override onlyAgent returns (bool) {
require(balanceOf(_lostWallet) != 0, "no tokens to recover");
IIdentity _onchainID = IIdentity(_investorOnchainID);
bytes32 _key = keccak256(abi.encode(_newWallet));
if (_onchainID.keyHasPurpose(_key, 1)) {
uint256 investorTokens = balanceOf(_lostWallet);
uint256 frozenTokens = _frozenTokens[_lostWallet];
_tokenIdentityRegistry.registerIdentity(_newWallet, _onchainID, _tokenIdentityRegistry.investorCountry
(_lostWallet));
_tokenIdentityRegistry.deleteIdentity(_lostWallet);
forcedTransfer(_lostWallet, _newWallet, investorTokens);
if (frozenTokens > 0) {
freezePartialTokens(_newWallet, frozenTokens);
}
if (_frozen[_lostWallet] == true) {
setAddressFrozen(_newWallet, true);
}
emit RecoverySuccess(_lostWallet, _newWallet, _investorOnchainID);
return true;
}
revert("Recovery not possible");
}
| 5,587,484 |
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
|
Reads the uint96 at `rdPtr` in returndata.
|
function readUint96(
ReturndataPointer rdPtr
) internal pure returns (uint96 value) {
assembly ("memory-safe") {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
| 8,451,890 |
/**
*Submitted for verification at Etherscan.io on 2021-04-03
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
// pragma experimental ABIEncoderV2;
contract Finance {
/// @notice EIP-20 token name for this token
string public constant name = "XAU.Finance";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "XAU";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 1000e18; // 1k Finance
/// @dev @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @dev @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Finance token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Finance::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Finance::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Finance::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Finance::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Finance::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Finance::delegateBySig: invalid nonce");
require(now <= expiry, "Finance::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Finance::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Finance::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Finance::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Finance::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Finance::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Finance::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Finance::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Finance::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
|
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Finance::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Finance::delegateBySig: invalid nonce");
require(now <= expiry, "Finance::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 15,339,580 |
./full_match/80001/0x1aa09F04f3497ECb85433Dfbd815B4728b47a3eB/sources/@solvprotocol/erc-3525/IERC721.sol
|
ERC-721 Non-Fungible Token Standard Note: the ERC-165 identifier for this interface is 0x80ac58cd./
|
interface 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) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
| 9,505,091 |
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File contracts/access/Context.sol
// SPDX-License-Identifier: MIT;
pragma solidity >=0.6.0 <=0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File contracts/security/Pausable.sol
pragma solidity >=0.6.0 <=0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File contracts/access/Ownable.sol
pragma solidity ^0.7.6;
/**
* @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 Pausable {
address public _owner;
address public _admin;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor(address ownerAddress) {
_owner = msg.sender;
_admin = ownerAddress;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyAdmin() {
require(_admin == _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 onlyAdmin {
emit OwnershipTransferred(_owner, _admin);
_owner = _admin;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File contracts/proxy/abstract/OwnableV2.sol
pragma solidity ^0.7.6;
abstract contract OwnableV2 {
function transferOwnership(address newOwner) external virtual;
function owner() external virtual returns (address);
}
// File contracts/proxy/abstract/AdminV2.sol
pragma solidity ^0.7.6;
abstract contract AdminV2 is OwnableV2 {
struct tokenInfo {
bool isExist;
uint8 decimal;
uint256 userStakeLimit;
uint256 maxStake;
uint256 lockableDays;
bool optionableStatus;
}
uint256 public stakeDuration;
uint256 public refPercentage;
uint256 public optionableBenefit;
mapping(address => address[]) public tokensSequenceList;
mapping(address => tokenInfo) public tokenDetails;
mapping(address => mapping(address => uint256)) public tokenDailyDistribution;
mapping(address => mapping(address => bool)) public tokenBlockedStatus;
function safeWithdraw(address tokenAddress, uint256 amount) external virtual;
}
// File contracts/proxy/abstract/Unifarm.sol
pragma solidity ^0.7.6;
abstract contract Unifarm is AdminV2 {
mapping(address => uint256) public totalStaking;
function viewStakingDetails(address _user)
public
view
virtual
returns (
address[] memory,
address[] memory,
bool[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory
);
}
// File contracts/libraries/SafeMath.sol
pragma solidity >=0.6.0 <=0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File contracts/abstract/IERC20.sol
pragma solidity >=0.6.0 <=0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/UnifarmV2Fixed.sol
pragma solidity ^0.7.6;
contract UnifarmV2Fixed is Ownable {
struct lockabelToken {
uint256 lockableDays;
bool optionableStatus;
}
Unifarm public uniV2;
using SafeMath for uint256;
uint256[] public intervalDays = [1, 8, 15, 22, 29, 36];
uint256 public constant DAYS = 1 days;
mapping(address => uint256) public totalUnStakingB;
mapping(address => uint256) public totalUnStakingA;
mapping(address => lockabelToken) public lockableDetailsB;
mapping(address => mapping(uint256 => bool)) public unstakeStatus;
event IntervalDaysDetails(uint256[] updatedIntervals, uint256 time);
event Claim(
address indexed userAddress,
address indexed stakedTokenAddress,
address indexed tokenAddress,
uint256 claimRewards,
uint256 time
);
event UnStake(
address indexed userAddress,
address indexed unStakedtokenAddress,
uint256 unStakedAmount,
uint256 time,
uint256 stakeID
);
event ReferralEarn(
address indexed userAddress,
address indexed callerAddress,
address indexed rewardTokenAddress,
uint256 rewardAmount,
uint256 time
);
event LockableTokenDetails(
address indexed tokenAddress,
uint256 lockableDys,
bool optionalbleStatus,
uint256 updatedTime
);
event WithdrawDetails(
address indexed tokenAddress,
uint256 withdrawalAmount,
uint256 time
);
constructor(address v2Address) Ownable(msg.sender) {
uniV2 = Unifarm(v2Address);
}
function init(address[] memory tokenAddress)
external
onlyOwner
returns (bool)
{
for (uint256 i = 0; i < tokenAddress.length; i++) {
transferFromContractV2(tokenAddress[i]);
}
return true;
}
function transferFromContractV2(address tokenAddress) internal {
uint256 bal = IERC20(tokenAddress).balanceOf(address(uniV2));
if (bal > 0) uniV2.safeWithdraw(tokenAddress, bal);
}
/**
* @notice send rewards
* @param stakedToken Stake amount of the user
* @param tokenAddress Reward token address
* @param amount Amount to be transferred as reward
*/
function sendToken(
address user,
address stakedToken,
address tokenAddress,
uint256 amount
) internal {
// Checks
if (tokenAddress != address(0)) {
require(
IERC20(tokenAddress).balanceOf(address(this)) >= amount,
"SEND: Insufficient Balance in Contract"
);
IERC20(tokenAddress).transfer(user, amount);
emit Claim(user, stakedToken, tokenAddress, amount, block.timestamp);
}
}
/**
* @notice Unstake and claim rewards
* @param stakeId Stake ID of the user
*/
function unStake(address user, uint256 stakeId) external whenNotPaused {
require(
msg.sender == user || msg.sender == _owner,
"UNSTAKE: Invalid User Entry"
);
(
,
address[] memory tokenAddress,
bool[] memory activeStatus,
,
uint256[] memory stakedAmount,
uint256[] memory startTime
) = (uniV2.viewStakingDetails(user));
// lockableDays check
require(
lockableDetailsB[tokenAddress[stakeId]].lockableDays <= block.timestamp,
"Token Locked"
);
// optional lock check
if (lockableDetailsB[tokenAddress[stakeId]].optionableStatus == true) {
require(
startTime[stakeId].add(uniV2.stakeDuration()) <= block.timestamp,
"Locked in optional lock"
);
}
// Checks
if (unstakeStatus[user][stakeId] == false && activeStatus[stakeId] == true)
unstakeStatus[user][stakeId] = true;
else revert("UNSTAKE : Unstaked Already");
// State updation
uint256 totalStaking =
uniV2.totalStaking(tokenAddress[stakeId]).sub(
totalUnStakingB[tokenAddress[stakeId]].add(
totalUnStakingA[tokenAddress[stakeId]]
)
);
totalUnStakingB[tokenAddress[stakeId]] = totalUnStakingB[
tokenAddress[stakeId]
]
.add(stakedAmount[stakeId]);
// Balance check
require(
IERC20(tokenAddress[stakeId]).balanceOf(address(this)) >=
stakedAmount[stakeId],
"UNSTAKE : Insufficient Balance"
);
IERC20(tokenAddress[stakeId]).transfer(user, stakedAmount[stakeId]);
claimRewards(user, stakeId, totalStaking);
// Emit state changes
emit UnStake(
user,
tokenAddress[stakeId],
stakedAmount[stakeId],
block.timestamp,
stakeId
);
}
function updateIntervalDays(uint256[] memory _interval) external onlyOwner {
intervalDays = new uint256[](0);
for (uint8 i = 0; i < _interval.length; i++) {
uint256 noD = uniV2.stakeDuration().div(DAYS);
require(noD > _interval[i], "Invalid Interval Day");
intervalDays.push(_interval[i]);
}
emit IntervalDaysDetails(intervalDays, block.timestamp);
}
function lockableToken(
address tokenAddress,
uint8 lockableStatus,
uint256 lockedDays,
bool optionableStatus
) external onlyOwner {
require(
lockableStatus == 1 || lockableStatus == 2 || lockableStatus == 3,
"Invalid Lockable Status"
);
(bool tokenExist, , , , , ) = uniV2.tokenDetails(tokenAddress);
require(tokenExist == true, "Token Not Exist");
if (lockableStatus == 1) {
lockableDetailsB[tokenAddress].lockableDays = block.timestamp.add(
lockedDays
);
} else if (lockableStatus == 2)
lockableDetailsB[tokenAddress].lockableDays = 0;
else if (lockableStatus == 3)
lockableDetailsB[tokenAddress].optionableStatus = optionableStatus;
emit LockableTokenDetails(
tokenAddress,
lockableDetailsB[tokenAddress].lockableDays,
lockableDetailsB[tokenAddress].optionableStatus,
block.timestamp
);
}
function transferV2Ownership(address newOwner) external onlyOwner {
uniV2.transferOwnership(newOwner);
}
function safeWithdraw(address tokenAddress, uint256 amount)
external
onlyOwner
{
require(
IERC20(tokenAddress).balanceOf(address(this)) >= amount,
"SAFEWITHDRAW: Insufficient Balance"
);
require(
IERC20(tokenAddress).transfer(_owner, amount) == true,
"SAFEWITHDRAW: Transfer failed"
);
emit WithdrawDetails(tokenAddress, amount, block.timestamp);
}
function updateV2Address(address v2Address)
external
onlyOwner
returns (bool)
{
uniV2 = Unifarm(v2Address);
return true;
}
function updateTotalUnstakingA(
address[] memory tokenAddress,
uint256[] memory tokenAmount
) external onlyOwner returns (bool) {
require(tokenAddress.length == tokenAmount.length, "Invalid Input");
for (uint8 i = 0; i < tokenAddress.length; i++) {
totalUnStakingA[tokenAddress[i]] = tokenAmount[i];
}
return true;
}
function totalStakingDetails(address tokenAddress)
external
view
returns (uint256)
{
uint256 totalStaking =
uniV2.totalStaking(tokenAddress).sub(
totalUnStakingB[tokenAddress].add(totalUnStakingA[tokenAddress])
);
return totalStaking;
}
function emergencyUnstake(
uint256 stakeId,
address userAddress,
address[] memory rewardtokens,
uint256[] memory amount
) external onlyOwner {
(
address[] memory referrerAddress,
address[] memory tokenAddress,
bool[] memory activeStatus,
,
uint256[] memory stakedAmount,
) = (uniV2.viewStakingDetails(userAddress));
// Checks
if (
unstakeStatus[userAddress][stakeId] == false &&
activeStatus[stakeId] == true
) unstakeStatus[userAddress][stakeId] = true;
else revert("EMERGENCY: Unstaked Already");
transferFromContractV2(tokenAddress[stakeId]);
// Balance check
require(
IERC20(tokenAddress[stakeId]).balanceOf(address(this)) >=
stakedAmount[stakeId],
"EMERGENCY : Insufficient Balance"
);
totalUnStakingB[tokenAddress[stakeId]] = totalUnStakingB[
tokenAddress[stakeId]
]
.add(stakedAmount[stakeId]);
IERC20(tokenAddress[stakeId]).transfer(userAddress, stakedAmount[stakeId]);
for (uint256 i = 0; i < rewardtokens.length; i++) {
require(
IERC20(rewardtokens[i]).balanceOf(address(this)) >= amount[i],
"EMERGENCY : Insufficient Reward Balance"
);
uint256 rewardsEarned = amount[i];
transferFromContractV2(rewardtokens[i]);
if (referrerAddress[stakeId] != address(0)) {
uint256 refEarned =
(rewardsEarned.mul(uniV2.refPercentage())).div(100 ether);
rewardsEarned = rewardsEarned.sub(refEarned);
require(
IERC20(rewardtokens[i]).transfer(referrerAddress[stakeId], refEarned),
"EMERGENCY : Transfer Failed"
);
emit ReferralEarn(
referrerAddress[stakeId],
userAddress,
rewardtokens[i],
refEarned,
block.timestamp
);
}
IERC20(rewardtokens[i]).transfer(userAddress, rewardsEarned);
}
// Emit state changes
emit UnStake(
userAddress,
tokenAddress[stakeId],
stakedAmount[stakeId],
block.timestamp,
stakeId
);
}
function lockContract(bool pauseStatus) external onlyOwner {
if (pauseStatus == true) _pause();
else if (pauseStatus == false) _unpause();
}
/**
* @notice Get rewards for one day
* @param stakedAmount Stake amount of the user
* @param stakedToken Staked token address of the user
* @param rewardToken Reward token address
* @param totalStake totalStakeAmount
* @return reward One dayh reward for the user
*/
function getOneDayReward(
uint256 stakedAmount,
address stakedToken,
address rewardToken,
uint256 totalStake
) public view returns (uint256 reward) {
uint256 lockBenefit;
if (lockableDetailsB[stakedToken].optionableStatus) {
stakedAmount = stakedAmount.mul(uniV2.optionableBenefit());
lockBenefit = stakedAmount.mul(uniV2.optionableBenefit().sub(1));
reward = (
stakedAmount.mul(uniV2.tokenDailyDistribution(stakedToken, rewardToken))
)
.div(totalStake.add(lockBenefit));
} else
reward = (
stakedAmount.mul(uniV2.tokenDailyDistribution(stakedToken, rewardToken))
)
.div(totalStake);
}
function claimRewards(
address user,
uint256 stakeId,
uint256 totalStaking
) internal {
(
address[] memory referrerAddress,
address[] memory tokenAddress,
,
,
uint256[] memory stakedAmount,
uint256[] memory startTime
) = (uniV2.viewStakingDetails(user));
// Local variables
uint256 interval;
uint256 endOfProfit;
interval = startTime[stakeId].add(uniV2.stakeDuration());
if (interval > block.timestamp) endOfProfit = block.timestamp;
else endOfProfit = startTime[stakeId].add(uniV2.stakeDuration());
interval = endOfProfit.sub(startTime[stakeId]);
// Reward calculation
if (interval >= DAYS)
_rewardCalculation(
user,
referrerAddress[stakeId],
tokenAddress[stakeId],
stakedAmount[stakeId],
interval,
totalStaking
);
}
function _rewardCalculation(
address user,
address referrerAddress,
address stakedToken,
uint256 stakedAmount,
uint256 interval,
uint256 totalStake
) internal {
uint256 rewardsEarned;
uint256 noOfDays;
noOfDays = interval.div(DAYS);
rewardsEarned = noOfDays.mul(
getOneDayReward(stakedAmount, stakedToken, stakedToken, totalStake)
);
// Referrer Earning
if (referrerAddress != address(0)) {
uint256 refEarned =
(rewardsEarned.mul(uniV2.refPercentage())).div(100 ether);
rewardsEarned = rewardsEarned.sub(refEarned);
require(
IERC20(stakedToken).transfer(referrerAddress, refEarned),
"Transfer Failed"
);
emit ReferralEarn(
referrerAddress,
user,
stakedToken,
refEarned,
block.timestamp
);
}
// Rewards Send
sendToken(user, stakedToken, stakedToken, rewardsEarned);
uint8 i = 1;
while (i < intervalDays.length) {
if (noOfDays >= intervalDays[i]) {
uint256 balDays = noOfDays.sub((intervalDays[i].sub(1)));
address rewardToken = uniV2.tokensSequenceList(stakedToken, i);
if (
rewardToken != stakedToken &&
uniV2.tokenBlockedStatus(stakedToken, rewardToken) == false
) {
rewardsEarned = balDays.mul(
getOneDayReward(stakedAmount, stakedToken, rewardToken, totalStake)
);
// Referrer Earning
if (referrerAddress != address(0)) {
uint256 refEarned =
(rewardsEarned.mul(uniV2.refPercentage())).div(100 ether);
rewardsEarned = rewardsEarned.sub(refEarned);
require(
IERC20(rewardToken).transfer(referrerAddress, refEarned),
"Transfer Failed"
);
emit ReferralEarn(
referrerAddress,
user,
rewardToken,
refEarned,
block.timestamp
);
}
// Rewards Send
sendToken(user, stakedToken, rewardToken, rewardsEarned);
}
i = i + 1;
} else {
break;
}
}
}
}
|
Get rewards for one day stakedAmount Stake amount of the user stakedToken Staked token address of the user rewardToken Reward token address totalStake totalStakeAmount return reward One dayh reward for the user/
|
function getOneDayReward(
uint256 stakedAmount,
address stakedToken,
address rewardToken,
uint256 totalStake
) public view returns (uint256 reward) {
uint256 lockBenefit;
if (lockableDetailsB[stakedToken].optionableStatus) {
stakedAmount = stakedAmount.mul(uniV2.optionableBenefit());
lockBenefit = stakedAmount.mul(uniV2.optionableBenefit().sub(1));
reward = (
stakedAmount.mul(uniV2.tokenDailyDistribution(stakedToken, rewardToken))
)
.div(totalStake.add(lockBenefit));
} else
reward = (
stakedAmount.mul(uniV2.tokenDailyDistribution(stakedToken, rewardToken))
)
.div(totalStake);
}
| 14,901,422 |
./full_match/1/0x426D747337eF5DAeebbaecfAf4f79C69F7bcAeeA/sources/temp-contracts/scoring/ScoreByCMCPegged20.sol
|
Given a sum score corresponding to the total CMC of the top three non-WETH/WBTC elements (the three other elements that we want to include), returns a value corresponding to 20% of said sum for pegged weights./
|
function peggedScore(uint256 subscore) internal pure returns(uint256) {
return (subscore.mul(20)).div(100e18);
}
| 9,798,428 |
./partial_match/1/0x3ef36D53A168c44ed2Ec7a98129CA0308BC1AE45/sources/DigiDinarStableToken.sol
|
ERC20 interface/
|
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);
Developed by Kuwaiti Coin Limited.
}
| 16,198,186 |
pragma solidity ^0.5.10;
/** @title A contract for generating unique identifiers
*
* @notice A contract that provides an identifier generation scheme,
* guaranteeing uniqueness across all contracts that inherit from it,
* as well as the unpredictability of future identifiers.
*
* @dev This contract is intended to be inherited by any contract that
* implements the callback software pattern for cooperative custodianship.
*
*/
contract LockRequestable {
// MEMBERS
/// @notice the count of all invocations of `generateLockId`.
uint256 public lockRequestCount;
// CONSTRUCTOR
constructor() public {
lockRequestCount = 0;
}
// FUNCTIONS
/** @notice Returns a fresh unique identifier.
*
* @dev the generation scheme uses three components.
* First, the blockhash of the previous block.
* Second, the deployed address.
* Third, the next value of the counter.
* This ensures that identifiers are unique across all contracts
* following this scheme, and that future identifiers are
* unpredictable.
*
* @return a 32-byte unique identifier.
*/
function generateLockId() internal returns (bytes32 lockId) {
return keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), ++lockRequestCount));
}
}
contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/** @title A dual control contract.
*
* @notice A general-purpose contract that implements dual control over
* co-operating contracts through a callback mechanism.
*
* @dev This contract implements dual control through a 2-of-N
* threshold multi-signature scheme. The contract recognizes a set of N signers,
* and will unlock requests with signatures from any distinct pair of them.
* This contract signals the unlocking through a co-operative callback
* scheme.
* This contract also provides time lock and revocation features.
* Requests made by a 'primary' account have a default time lock applied.
* All other requests must pay a 1 ETH stake and have an extended time lock
* applied.
* A request that is completed will prevent all previous pending requests
* that share the same callback from being completed: this is the
* revocation feature.
*
*/
contract Custodian {
// TYPES
/** @dev The `Request` struct stores a pending unlocking.
* `callbackAddress` and `callbackSelector` are the data required to
* make a callback. The custodian completes the process by
* calling `callbackAddress.call(callbackSelector, lockId)`, which
* signals to the contract co-operating with the Custodian that
* the 2-of-N signatures have been provided and verified.
*/
struct Request {
bytes32 lockId;
bytes4 callbackSelector; // bytes4 and address can be packed into 1 word
address callbackAddress;
uint256 idx;
uint256 timestamp;
bool extended;
}
// EVENTS
/// @dev Emitted by successful `requestUnlock` calls.
event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
/// @dev Emitted by `completeUnlock` calls on requests in the time-locked state.
event TimeLocked(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
/// @dev Emitted by successful `completeUnlock` calls.
event Completed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by `completeUnlock` calls where the callback failed.
event Failed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by successful `extendRequestTimeLock` calls.
event TimeLockExtended(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
// MEMBERS
/** @dev The count of all requests.
* This value is used as a nonce, incorporated into the request hash.
*/
uint256 public requestCount;
/// @dev The set of signers: signatures from two signers unlock a pending request.
mapping (address => bool) public signerSet;
/// @dev The map of request hashes to pending requests.
mapping (bytes32 => Request) public requestMap;
/// @dev The map of callback addresses to callback selectors to request indexes.
mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs;
/** @dev The default period (in seconds) to time-lock requests.
* All requests will be subject to this default time lock, and the duration
* is fixed at contract creation.
*/
uint256 public defaultTimeLock;
/** @dev The extended period (in seconds) to time-lock requests.
* Requests not from the primary account are subject to this time lock.
* The primary account may also elect to extend the time lock on requests
* that originally received the default.
*/
uint256 public extendedTimeLock;
/// @dev The primary account is the privileged account for making requests.
address public primary;
// CONSTRUCTOR
constructor(
address[] memory _signers,
uint256 _defaultTimeLock,
uint256 _extendedTimeLock,
address _primary
)
public
{
// check for at least two `_signers`
require(_signers.length >= 2, "at least two `_signers`");
// validate time lock params
require(_defaultTimeLock <= _extendedTimeLock, "valid timelock params");
defaultTimeLock = _defaultTimeLock;
extendedTimeLock = _extendedTimeLock;
primary = _primary;
// explicitly initialize `requestCount` to zero
requestCount = 0;
// turn the array into a set
for (uint i = 0; i < _signers.length; i++) {
// no zero addresses or duplicates
require(_signers[i] != address(0) && !signerSet[_signers[i]], "no zero addresses or duplicates");
signerSet[_signers[i]] = true;
}
}
// MODIFIERS
modifier onlyPrimary {
require(msg.sender == primary, "only primary");
_;
}
modifier onlySigner {
require(signerSet[msg.sender], "only signer");
_;
}
// METHODS
/** @notice Requests an unlocking with a lock identifier and a callback.
*
* @dev If called by an account other than the primary a 1 ETH stake
* must be paid. When the request is unlocked stake will be transferred to the message sender.
* This is an anti-spam measure. As well as the callback
* and the lock identifier parameters a 'whitelisted address' is required
* for compatibility with existing signature schemes.
*
* @param _lockId The identifier of a pending request in a co-operating contract.
* @param _callbackAddress The address of a co-operating contract.
* @param _callbackSelector The function selector of a function within
* the co-operating contract at address `_callbackAddress`.
* @param _whitelistedAddress An address whitelisted in existing
* offline control protocols.
*
* @return requestMsgHash The hash of a request message to be signed.
*/
function requestUnlock(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
address _whitelistedAddress
)
public
payable
returns (bytes32 requestMsgHash)
{
require(msg.sender == primary || msg.value >= 1 ether, "sender is primary or stake is paid");
// disallow using a zero value for the callback address
require(_callbackAddress != address(0), "no zero value for callback address");
uint256 requestIdx = ++requestCount;
// compute a nonce value
// - the blockhash prevents prediction of future nonces
// - the address of this contract prevents conflicts with co-operating contracts using this scheme
// - the counter prevents conflicts arising from multiple txs within the same block
uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx)));
requestMsgHash = keccak256(
abi.encodePacked(
nonce,
_whitelistedAddress,
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
requestMap[requestMsgHash] = Request({
lockId: _lockId,
callbackSelector: _callbackSelector,
callbackAddress: _callbackAddress,
idx: requestIdx,
timestamp: block.timestamp,
extended: false
});
// compute the expiry time
uint256 timeLockExpiry = block.timestamp;
if (msg.sender == primary) {
timeLockExpiry += defaultTimeLock;
} else {
timeLockExpiry += extendedTimeLock;
// any sender that is not the creator will get the extended time lock
requestMap[requestMsgHash].extended = true;
}
emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry);
}
/** @notice Completes a pending unlocking with two signatures.
*
* @dev Given a request message hash as two signatures of it from
* two distinct signers in the signer set, this function completes the
* unlocking of the pending request by executing the callback.
*
* @param _requestMsgHash The request message hash of a pending request.
* @param _recoveryByte1 The public key recovery byte (27 or 28)
* @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair
* @param _recoveryByte2 The public key recovery byte (27 or 28)
* @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair
*
* @return success True if the callback successfully executed.
*/
function completeUnlock(
bytes32 _requestMsgHash,
uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1,
uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2
)
public
onlySigner
returns (bool success)
{
Request storage request = requestMap[_requestMsgHash];
// copy storage to locals before `delete`
bytes32 lockId = request.lockId;
address callbackAddress = request.callbackAddress;
bytes4 callbackSelector = request.callbackSelector;
// failing case of the lookup if the callback address is zero
require(callbackAddress != address(0), "no zero value for callback address");
// reject confirms of earlier withdrawals buried under later confirmed withdrawals
require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector],
"reject confirms of earlier withdrawals buried under later confirmed withdrawals");
address signer1 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte1,
_ecdsaR1,
_ecdsaS1
);
require(signerSet[signer1], "signer is set");
address signer2 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte2,
_ecdsaR2,
_ecdsaS2
);
require(signerSet[signer2], "signer is set");
require(signer1 != signer2, "signers are different");
if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) {
emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash);
return false;
} else if ((block.timestamp - request.timestamp) < defaultTimeLock) {
emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash);
return false;
} else {
if (address(this).balance > 0) {
// reward sender with anti-spam payments
msg.sender.transfer(address(this).balance);
}
// raise the waterline for the last completed unlocking
lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx;
// and delete the request
delete requestMap[_requestMsgHash];
// invoke callback
(success,) = (false, bytes(msg.data));
callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId)); //inject UNHANDLED EXCEPTION
if (success) {
emit Completed(lockId, _requestMsgHash, signer1, signer2);
} else {
emit Failed(lockId, _requestMsgHash, signer1, signer2);
}
}
}
/** @notice Reclaim the storage of a pending request that is uncompletable.
*
* @dev If a pending request shares the callback (address and selector) of
* a later request has been completed, then the request can no longer
* be completed. This function will reclaim the contract storage of the
* pending request.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function deleteUncompletableRequest(bytes32 _requestMsgHash) public {
Request storage request = requestMap[_requestMsgHash];
uint256 idx = request.idx;
require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector],
"there must be a completed latter request with same callback");
delete requestMap[_requestMsgHash];
}
/** @notice Extend the time lock of a pending request.
*
* @dev Requests made by the primary account receive the default time lock.
* This function allows the primary account to apply the extended time lock
* to one its own requests.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {
Request storage request = requestMap[_requestMsgHash];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_requestMsgHash` is received
require(request.callbackAddress != address(0), "reject 1null1 results from the map lookup");
// `extendRequestTimeLock` must be idempotent
require(request.extended != true, "`extendRequestTimeLock` must be idempotent");
// set the `extended` flag; note that this is never unset
request.extended = true;
emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);
}
}
/** @title A contract to inherit upgradeable custodianship.
*
* @notice A contract that provides re-usable code for upgradeable
* custodianship. That custodian may be an account or another contract.
*
* @dev This contract is intended to be inherited by any contract
* requiring a custodian to control some aspect of its functionality.
* This contract provides the mechanism for that custodianship to be
* passed from one custodian to the next.
*
*/
contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian, "only custodian");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0), "no null value for `_proposedCustodian`");
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
/** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup");
return changeRequest.proposedNew;
}
//EVENTS
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
}
/** @title A contract to inherit upgradeable token implementations.
*
* @notice A contract that provides re-usable code for upgradeable
* token implementations. It itself inherits from `CustodianUpgradable`
* as the upgrade process is controlled by the custodian.
*
* @dev This contract is intended to be inherited by any contract
* requiring a reference to the active token implementation, either
* to delegate calls to it, or authorize calls from it. This contract
* provides the mechanism for that implementation to be replaced,
* which constitutes an implementation upgrade.
*
*/
contract ERC20ImplUpgradeable is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending implementation changes.
struct ImplChangeRequest {
address proposedNew;
}
// MEMBERS
// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The map of lock ids to pending implementation changes.
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
// CONSTRUCTOR
constructor(address _custodian) CustodianUpgradeable(_custodian) public {
erc20Impl = ERC20Impl(0x0);
}
// MODIFIERS
modifier onlyImpl {
require(msg.sender == address(erc20Impl), "only ERC20Impl");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the active implementation associated
* with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedImpl The address of the new active implementation.
* @return lockId A unique identifier for this request.
*/
function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0), "no null value for `_proposedImpl`");
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
/** @notice Confirms a pending change of the active implementation
* associated with this contract.
*
* @dev When called by the custodian with a lock id associated with a
* pending change, the `ERC20Impl erc20Impl` member will be updated
* with the requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
// PRIVATE FUNCTIONS
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup");
return ERC20Impl(changeRequest.proposedNew);
}
//EVENTS
/// @dev Emitted by successful `requestImplChange` calls.
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl
);
/// @dev Emitted by successful `confirmImplChange` calls.
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
}
/** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/
contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with an address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
}
/** @title ERC20 compliant token balance store.
*
* @notice This contract serves as the store of balances, allowances, and
* supply for the ERC20 compliant token. No business logic exists here.
*
* @dev This contract contains no business logic and instead
* is the final destination for any change in balances, allowances, or token
* supply. This contract is upgradeable in the sense that its custodian can
* update the `erc20Impl` address, thus redirecting the source of logic that
* determines how the balances will be updated.
*
*/
contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// @dev The total token supply.
uint256 public totalSupply;
/// @dev The mapping of balances.
mapping (address => uint256) public balances;
/// @dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
/** @notice The function to set the total supply of tokens.
*
* @dev Intended for use by token implementation functions
* that update the total supply. The only authorized caller
* is the active implementation.
*
* @param _newTotalSupply the value to set as the new total supply
*/
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
/** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
/** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
/** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
}
/** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/
contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweeping message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0), "no null value for `_sweeper`");
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy), "only ERC20Proxy");
_;
}
modifier onlySweeper {
require(msg.sender == sweeper, "only sweeper");
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in a proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0), "no null value for `_spender`");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_spender] != true, "_spender must not be blocked");
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0),"no null value for_spender");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_spender] != true, "_spender must not be blocked");
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance, "new allowance must not be smaller than previous");
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0), "no unspendable approvals"); // disallow unspendable approvals
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_spender] != true, "_spender must not be blocked");
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance, "new allowance must not be smaller than previous");
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0), "no null value for `_receiver`");
require(blocked[msg.sender] != true, "account blocked");
require(blocked[_receiver] != true, "_receiver must not be blocked");
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0), "unknown `_lockId`");
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true, "account blocked");
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender, "disallow burning more, than amount of the balance");
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If the suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, _value, balance - _value);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, _value, balance, 0);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length, "_tos and _values must be the same length");
require(blocked[msg.sender] != true, "account blocked");
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0), "no null values for _tos");
require(blocked[to] != true, "_tos must not be blocked");
uint256 v = _values[i];
require(senderBalance >= v, "insufficient funds");
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transferred to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0), "no null value for `_to`");
require(blocked[_to] != true, "_to must not be blocked");
require((_vs.length == _rs.length) && (_vs.length == _ss.length), "_vs[], _rs[], _ss lengths are different");
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true, "_froms must not be blocked");
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0), "no null value for `_to`");
require(blocked[_to] != true, "_to must not be blocked");
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true, "_froms must not be blocked");
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in a proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0), "no null values for `_to`");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_from] != true, "_from must not be blocked");
require(blocked[_to] != true, "_to must not be blocked");
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom, "insufficient funds on `_from` balance");
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance, "insufficient allowance amount");
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in a proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0), "no null value for `_to`");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_to] != true, "_to must not be blocked");
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender, "insufficient funds");
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Transfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transferred.
*
* @dev If the suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to transfer.
*
* @return success true if the transfer succeeded.
*/
function forceTransfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0), "no null value for `_to`");
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
/** @dev Emitted by successful `confirmWipe` calls.
*
* @param _value Amount requested to be burned.
*
* @param _burned Amount which was burned.
*
* @param _balance Amount left on account after burn.
*
* @param _from Account which balance was burned.
*/
event Wiped(address _from, uint256 _value, uint256 _burned, uint _balance);
}
/** @title A contact to govern hybrid control over increases to the token supply and managing accounts.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the 1true1 custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'controller') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/
contract Controller is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending force transfer requests.
struct forceTransferRequest {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or force transferring funds from them.
*/
address public controller;
/** @dev The maximum that the token supply can be increased to
* through the use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'controller' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending force transfer requests.
mapping (bytes32 => forceTransferRequest) public pendingForceTransferRequestMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _controller,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
controller = _controller;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian), "only custodian");
_;
}
modifier onlyController {
require(msg.sender == controller, "only controller");
_;
}
modifier onlySigner {
require(custodian.signerSet(msg.sender) == true, "only signer");
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyController {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply, "new total supply overflow");
require(newTotalSupply <= totalSupplyCeiling, "total supply ceiling overflow");
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only controller can call this function, and only the custodian
* can confirm the request.
*
* @param _froms The array of suspected accounts.
*
* @param _values array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _froms, uint256[] memory _values) public onlyController returns (bytes32 lockId) {
require(_froms.length == _values.length, "_froms[] and _values[] must be same length");
lockId = generateLockId();
uint256 amount = _froms.length;
for(uint256 i = 0; i < amount; i++) {
address from = _froms[i];
uint256 value = _values[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests force transfer from the suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only controller can call this function, and only the custodian
* can confirm the request.
*
* @param _from address of suspected account.
*
* @param _to address of reciever.
*
* @param _value amount which will be transferred.
*
* @return lockId A unique identifier for this request.
*/
function requestForceTransfer(address _from, address _to, uint256 _value) public onlyController returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0, "no zero value transfers");
pendingForceTransferRequestMap[lockId] = forceTransferRequest(_value, _from, _to);
emit ForceTransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending force transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is transferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmForceTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingForceTransferRequestMap[_lockId].from;
address to = pendingForceTransferRequestMap[_lockId].to;
uint256 value = pendingForceTransferRequestMap[_lockId].value;
delete pendingForceTransferRequestMap[_lockId];
erc20Impl.forceTransfer(from, to, value);
emit ForceTransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0, "no zero ceiling raise");
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0, "no gibberish _lockId");
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the controller.
*
* @dev The controller is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyController {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling, "totalSupplyCeiling overflow");
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with a wallet.
*
* @dev Only signers from custodian are authorized to call this function
*
* @param wallet account which will be blocked.
*/
function blockWallet(address wallet) public onlySigner {
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with a wallet.
*
* @dev Only signers from custodian are authorized to call this function
*
* @param wallet account which will be unblocked.
*/
function unblockWallet(address wallet) public onlySigner {
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `blockWallet` calls.
event Blocked(address _wallet);
/// @dev Emitted by successful `unblockWallet` calls.
event Unblocked(address _wallet);
/// @dev Emitted by successful `requestForceTransfer` calls.
event ForceTransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmForceTransfer` calls.
event ForceTransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
}
|
Requests an increase in the token supply, with the newly created tokens to be added to the balance of the specified account. Returns a unique lock id associated with the request. Anyone can call this function, but confirming the request is authorized by the custodian. NOTE: printing to the zero address is disallowed. _receiver The receiving address of the print, if confirmed. _value The number of tokens to add to the total supply and the balance of the receiving address, if confirmed. return lockId A unique identifier for this request./
|
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0), "no null value for `_receiver`");
require(blocked[msg.sender] != true, "account blocked");
require(blocked[_receiver] != true, "_receiver must not be blocked");
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
| 12,961,537 |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/SafeMath96.sol
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath96 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint96 a, uint256 b) internal pure returns (uint96) {
require(uint256(uint96(b)) == b, "SafeMath: addition overflow");
uint96 c = a + uint96(b);
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint96 a, uint256 b) internal pure returns (uint96) {
require(uint256(uint96(b)) == b, "SafeMath: subtraction overflow");
return sub(a, uint96(b), "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
uint96 c = a - b;
return c;
}
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/spec_interfaces/ICommittee.sol
pragma solidity 0.6.12;
/// @title Committee contract interface
interface ICommittee {
event CommitteeChange(address indexed addr, uint256 weight, bool certification, bool inCommittee);
event CommitteeSnapshot(address[] addrs, uint256[] weights, bool[] certification);
// No external functions
/*
* External functions
*/
/// Notifies a weight change of a member
/// @dev Called only by: Elections contract
/// @param addr is the committee member address
/// @param weight is the updated weight of the committee member
function memberWeightChange(address addr, uint256 weight) external /* onlyElectionsContract onlyWhenActive */;
/// Notifies a change in the certification of a member
/// @dev Called only by: Elections contract
/// @param addr is the committee member address
/// @param isCertified is the updated certification state of the member
function memberCertificationChange(address addr, bool isCertified) external /* onlyElectionsContract onlyWhenActive */;
/// Notifies a member removal for example due to voteOut or voteUnready
/// @dev Called only by: Elections contract
/// @param memberRemoved is the removed committee member address
/// @return memberRemoved indicates whether the member was removed from the committee
/// @return removedMemberWeight indicates the removed member weight
/// @return removedMemberCertified indicates whether the member was in the certified committee
function removeMember(address addr) external returns (bool memberRemoved, uint removedMemberWeight, bool removedMemberCertified)/* onlyElectionContract */;
/// Notifies a new member applicable for committee (due to registration, unbanning, certification change)
/// The new member will be added only if it is qualified to join the committee
/// @dev Called only by: Elections contract
/// @param addr is the added committee member address
/// @param weight is the added member weight
/// @param isCertified is the added member certification state
/// @return memberAdded bool indicates whether the member was added
function addMember(address addr, uint256 weight, bool isCertified) external returns (bool memberAdded) /* onlyElectionsContract */;
/// Checks if addMember() would add a the member to the committee (qualified to join)
/// @param addr is the candidate committee member address
/// @param weight is the candidate committee member weight
/// @return wouldAddMember bool indicates whether the member will be added
function checkAddMember(address addr, uint256 weight) external view returns (bool wouldAddMember);
/// Returns the committee members and their weights
/// @return addrs is the committee members list
/// @return weights is an array of uint, indicating committee members list weight
/// @return certification is an array of bool, indicating the committee members certification status
function getCommittee() external view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification);
/// Returns the currently appointed committee data
/// @return generalCommitteeSize is the number of members in the committee
/// @return certifiedCommitteeSize is the number of certified members in the committee
/// @return totalWeight is the total effective stake (weight) of the committee
function getCommitteeStats() external view returns (uint generalCommitteeSize, uint certifiedCommitteeSize, uint totalWeight);
/// Returns a committee member data
/// @param addr is the committee member address
/// @return inCommittee indicates whether the queried address is a member in the committee
/// @return weight is the committee member weight
/// @return isCertified indicates whether the committee member is certified
/// @return totalCommitteeWeight is the total weight of the committee.
function getMemberInfo(address addr) external view returns (bool inCommittee, uint weight, bool isCertified, uint totalCommitteeWeight);
/// Emits a CommitteeSnapshot events with current committee info
/// @dev a CommitteeSnapshot is useful on contract migration or to remove the need to track past events.
function emitCommitteeSnapshot() external;
/*
* Governance functions
*/
event MaxCommitteeSizeChanged(uint8 newValue, uint8 oldValue);
/// Sets the maximum number of committee members
/// @dev governance function called only by the functional manager
/// @dev when reducing the number of members, the bottom ones are removed from the committee
/// @param _maxCommitteeSize is the maximum number of committee members
function setMaxCommitteeSize(uint8 _maxCommitteeSize) external /* onlyFunctionalManager */;
/// Returns the maximum number of committee members
/// @return maxCommitteeSize is the maximum number of committee members
function getMaxCommitteeSize() external view returns (uint8);
/// Imports the committee members from a previous committee contract during migration
/// @dev initialization function called only by the initializationManager
/// @dev does not update the reward contract to avoid incorrect notifications
/// @param previousCommitteeContract is the address of the previous committee contract
function importMembers(ICommittee previousCommitteeContract) external /* onlyInitializationAdmin */;
}
// File: contracts/spec_interfaces/IProtocolWallet.sol
pragma solidity 0.6.12;
/// @title Protocol Wallet interface
interface IProtocolWallet {
event FundsAddedToPool(uint256 added, uint256 total);
/*
* External functions
*/
/// Returns the address of the underlying staked token
/// @return balance is the wallet balance
function getBalance() external view returns (uint256 balance);
/// Transfers the given amount of orbs tokens form the sender to this contract and updates the pool
/// @dev assumes the caller approved the amount prior to calling
/// @param amount is the amount to add to the wallet
function topUp(uint256 amount) external;
/// Withdraws from pool to the client address, limited by the pool's MaxRate.
/// @dev may only be called by the wallet client
/// @dev no more than MaxRate x time period since the last withdraw may be withdrawn
/// @dev allocation that wasn't withdrawn can not be withdrawn in the next call
/// @param amount is the amount to withdraw
function withdraw(uint256 amount) external; /* onlyClient */
/*
* Governance functions
*/
event ClientSet(address client);
event MaxAnnualRateSet(uint256 maxAnnualRate);
event EmergencyWithdrawal(address addr, address token);
event OutstandingTokensReset(uint256 startTime);
/// Sets a new annual withdraw rate for the pool
/// @dev governance function called only by the migration owner
/// @dev the rate for a duration is duration x annualRate / 1 year
/// @param _annualRate is the maximum annual rate that can be withdrawn
function setMaxAnnualRate(uint256 _annualRate) external; /* onlyMigrationOwner */
/// Returns the annual withdraw rate of the pool
/// @return annualRate is the maximum annual rate that can be withdrawn
function getMaxAnnualRate() external view returns (uint256);
/// Resets the outstanding tokens to new start time
/// @dev governance function called only by the migration owner
/// @dev the next duration will be calculated starting from the given time
/// @param startTime is the time to set as the last withdrawal time
function resetOutstandingTokens(uint256 startTime) external; /* onlyMigrationOwner */
/// Emergency withdraw the wallet funds
/// @dev governance function called only by the migration owner
/// @dev used in emergencies, when a migration to a new wallet is needed
/// @param erc20 is the erc20 address of the token to withdraw
function emergencyWithdraw(address erc20) external; /* onlyMigrationOwner */
/// Sets the address of the client that can withdraw funds
/// @dev governance function called only by the functional owner
/// @param _client is the address of the new client
function setClient(address _client) external; /* onlyFunctionalOwner */
}
// File: contracts/spec_interfaces/IStakingRewards.sol
pragma solidity 0.6.12;
/// @title Staking rewards contract interface
interface IStakingRewards {
event DelegatorStakingRewardsAssigned(address indexed delegator, uint256 amount, uint256 totalAwarded, address guardian, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta);
event GuardianStakingRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta, uint256 stakingRewardsPerWeight, uint256 stakingRewardsPerWeightDelta);
event StakingRewardsClaimed(address indexed addr, uint256 claimedDelegatorRewards, uint256 claimedGuardianRewards, uint256 totalClaimedDelegatorRewards, uint256 totalClaimedGuardianRewards);
event StakingRewardsAllocated(uint256 allocatedRewards, uint256 stakingRewardsPerWeight);
event GuardianDelegatorsStakingRewardsPercentMilleUpdated(address indexed guardian, uint256 delegatorsStakingRewardsPercentMille);
/*
* External functions
*/
/// Returns the current reward balance of the given address.
/// @dev calculates the up to date balances (differ from the state)
/// @param addr is the address to query
/// @return delegatorStakingRewardsBalance the rewards awarded to the guardian role
/// @return guardianStakingRewardsBalance the rewards awarded to the guardian role
function getStakingRewardsBalance(address addr) external view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance);
/// Claims the staking rewards balance of an addr, staking the rewards
/// @dev Claimed rewards are staked in the staking contract using the distributeRewards interface
/// @dev includes the rewards for both the delegator and guardian roles
/// @dev calculates the up to date rewards prior to distribute them to the staking contract
/// @param addr is the address to claim rewards for
function claimStakingRewards(address addr) external;
/// Returns the current global staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @return stakingRewardsPerWeight is the potential reward per 1E18 (TOKEN_BASE) committee weight assigned to a guardian was in the committee from day zero
/// @return unclaimedStakingRewards is the of tokens that were assigned to participants and not claimed yet
function getStakingRewardsState() external view returns (
uint96 stakingRewardsPerWeight,
uint96 unclaimedStakingRewards
);
/// Returns the current guardian staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @dev notice that the guardian rewards are the rewards for the guardian role as guardian and do not include delegation rewards
/// @dev use getDelegatorStakingRewardsData to get the guardian's rewards as delegator
/// @param guardian is the guardian to query
/// @return balance is the staking rewards balance for the guardian role
/// @return claimed is the staking rewards for the guardian role that were claimed
/// @return delegatorRewardsPerToken is the potential reward per token (1E18 units) assigned to a guardian's delegator that delegated from day zero
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last guardian update
/// @return lastStakingRewardsPerWeight is the up to date stakingRewardsPerWeight used for the guardian state calculation
/// @return stakingRewardsPerWeightDelta is the increment in stakingRewardsPerWeight since the last guardian update
function getGuardianStakingRewardsData(address guardian) external view returns (
uint256 balance,
uint256 claimed,
uint256 delegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta,
uint256 lastStakingRewardsPerWeight,
uint256 stakingRewardsPerWeightDelta
);
/// Returns the current delegator staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @param delegator is the delegator to query
/// @return balance is the staking rewards balance for the delegator role
/// @return claimed is the staking rewards for the delegator role that were claimed
/// @return guardian is the guardian the delegator delegated to receiving a portion of the guardian staking rewards
/// @return lastDelegatorRewardsPerToken is the up to date delegatorRewardsPerToken used for the delegator state calculation
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last delegator update
function getDelegatorStakingRewardsData(address delegator) external view returns (
uint256 balance,
uint256 claimed,
address guardian,
uint256 lastDelegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta
);
/// Returns an estimation for the delegator and guardian staking rewards for a given duration
/// @dev the returned value is an estimation, assuming no change in the PoS state
/// @dev the period calculated for start from the current block time until the current time + duration.
/// @param addr is the address to estimate rewards for
/// @param duration is the duration to calculate for in seconds
/// @return estimatedDelegatorStakingRewards is the estimated reward for the delegator role
/// @return estimatedGuardianStakingRewards is the estimated reward for the guardian role
function estimateFutureRewards(address addr, uint256 duration) external view returns (
uint256 estimatedDelegatorStakingRewards,
uint256 estimatedGuardianStakingRewards
);
/// Sets the guardian's delegators staking reward portion
/// @dev by default uses the defaultDelegatorsStakingRewardsPercentMille
/// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille)
function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external;
/// Returns a guardian's delegators staking reward portion
/// @dev If not explicitly set, returns the defaultDelegatorsStakingRewardsPercentMille
/// @return delegatorRewardsRatioPercentMille is the delegators portion in percent-mille
function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external view returns (uint256 delegatorRewardsRatioPercentMille);
/// Returns the amount of ORBS tokens in the staking rewards wallet allocated to staking rewards
/// @dev The staking wallet balance must always larger than the allocated value
/// @return allocated is the amount of tokens allocated in the staking rewards wallet
function getStakingRewardsWalletAllocatedTokens() external view returns (uint256 allocated);
/// Returns the current annual staking reward rate
/// @dev calculated based on the current total committee weight
/// @return annualRate is the current staking reward rate in percent-mille
function getCurrentStakingRewardsRatePercentMille() external view returns (uint256 annualRate);
/// Notifies an expected change in the committee membership of the guardian
/// @dev Called only by: the Committee contract
/// @dev called upon expected change in the committee membership of the guardian
/// @dev triggers update of the global rewards state and the guardian rewards state
/// @dev updates the rewards state based on the committee state prior to the change
/// @param guardian is the guardian who's committee membership is updated
/// @param weight is the weight of the guardian prior to the change
/// @param totalCommitteeWeight is the total committee weight prior to the change
/// @param inCommittee indicates whether the guardian was in the committee prior to the change
/// @param inCommitteeAfter indicates whether the guardian is in the committee after the change
function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external /* onlyCommitteeContract */;
/// Notifies an expected change in a delegator and his guardian delegation state
/// @dev Called only by: the Delegation contract
/// @dev called upon expected change in a delegator's delegation state
/// @dev triggers update of the global rewards state, the guardian rewards state and the delegator rewards state
/// @dev on delegation change, updates also the new guardian and the delegator's lastDelegatorRewardsPerToken accordingly
/// @param guardian is the delegator's guardian prior to the change
/// @param guardianDelegatedStake is the delegated stake of the delegator's guardian prior to the change
/// @param delegator is the delegator about to change delegation state
/// @param delegatorStake is the stake of the delegator
/// @param nextGuardian is the delegator's guardian after to the change
/// @param nextGuardianDelegatedStake is the delegated stake of the delegator's guardian after to the change
function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external /* onlyDelegationsContract */;
/*
* Governance functions
*/
event AnnualStakingRewardsRateChanged(uint256 annualRateInPercentMille, uint256 annualCap);
event DefaultDelegatorsStakingRewardsChanged(uint32 defaultDelegatorsStakingRewardsPercentMille);
event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille);
event RewardDistributionActivated(uint256 startTime);
event RewardDistributionDeactivated();
event StakingRewardsBalanceMigrated(address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards, address toRewardsContract);
event StakingRewardsBalanceMigrationAccepted(address from, address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards);
event EmergencyWithdrawal(address addr, address token);
/// Activates staking rewards allocation
/// @dev governance function called only by the initialization admin
/// @dev On migrations, startTime should be set to the previous contract deactivation time
/// @param startTime sets the last assignment time
function activateRewardDistribution(uint startTime) external /* onlyInitializationAdmin */;
/// Deactivates fees and bootstrap allocation
/// @dev governance function called only by the migration manager
/// @dev guardians updates remain active based on the current perMember value
function deactivateRewardDistribution() external /* onlyMigrationManager */;
/// Sets the default delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille)
function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
/// Returns the default delegators staking reward portion
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
function getDefaultDelegatorsStakingRewardsPercentMille() external view returns (uint32);
/// Sets the maximum delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000)
function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
/// Returns the default delegators staking reward portion
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
function getMaxDelegatorsStakingRewardsPercentMille() external view returns (uint32);
/// Sets the annual rate and cap for the staking reward
/// @dev governance function called only by the functional manager
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external /* onlyFunctionalManager */;
/// Returns the annual staking reward rate
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
function getAnnualStakingRewardsRatePercentMille() external view returns (uint32);
/// Returns the annual staking rewards cap
/// @return annualStakingRewardsCap is the annual rate in percent-mille
function getAnnualStakingRewardsCap() external view returns (uint256);
/// Checks if rewards allocation is active
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function isRewardAllocationActive() external view returns (bool);
/// Returns the contract's settings
/// @return annualStakingRewardsCap is the annual rate in percent-mille
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function getSettings() external view returns (
uint annualStakingRewardsCap,
uint32 annualStakingRewardsRatePercentMille,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
bool rewardAllocationActive
);
/// Migrates the staking rewards balance of the given addresses to a new staking rewards contract
/// @dev The new rewards contract is determined according to the contracts registry
/// @dev No impact of the calling contract if the currently configured contract in the registry
/// @dev may be called also while the contract is locked
/// @param addrs is the list of addresses to migrate
function migrateRewardsBalance(address[] calldata addrs) external;
/// Accepts addresses balance migration from a previous rewards contract
/// @dev the function may be called by any caller that approves the amounts provided for transfer
/// @param addrs is the list migrated addresses
/// @param migratedGuardianStakingRewards is the list of received guardian rewards balance for each address
/// @param migratedDelegatorStakingRewards is the list of received delegator rewards balance for each address
/// @param totalAmount is the total amount of staking rewards migrated for all addresses in the list. Must match the sum of migratedGuardianStakingRewards and migratedDelegatorStakingRewards lists.
function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external;
/// Performs emergency withdrawal of the contract balance
/// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens
/// @dev governance function called only by the migration manager
/// @param erc20 is the ERC20 token to withdraw
function emergencyWithdraw(address erc20) external /* onlyMigrationManager */;
}
// File: contracts/spec_interfaces/IDelegations.sol
pragma solidity 0.6.12;
/// @title Delegations contract interface
interface IDelegations /* is IStakeChangeNotifier */ {
// Delegation state change events
event DelegatedStakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, address indexed delegator, uint256 delegatorContributedStake);
// Function calls
event Delegated(address indexed from, address indexed to);
/*
* External functions
*/
/// Delegate your stake
/// @dev updates the election contract on the changes in the delegated stake
/// @dev updates the rewards contract on the upcoming change in the delegator's delegation state
/// @param to is the address to delegate to
function delegate(address to) external /* onlyWhenActive */;
/// Refresh the address stake for delegation power based on the staking contract
/// @dev Disabled stake change update notifications from the staking contract may create mismatches
/// @dev refreshStake re-syncs the stake data with the staking contract
/// @param addr is the address to refresh its stake
function refreshStake(address addr) external /* onlyWhenActive */;
/// Refresh the addresses stake for delegation power based on the staking contract
/// @dev Batched version of refreshStake
/// @dev Disabled stake change update notifications from the staking contract may create mismatches
/// @dev refreshStakeBatch re-syncs the stake data with the staking contract
/// @param addrs is the list of addresses to refresh their stake
function refreshStakeBatch(address[] calldata addrs) external /* onlyWhenActive */;
/// Returns the delegate address of the given address
/// @param addr is the address to query
/// @return delegation is the address the addr delegated to
function getDelegation(address addr) external view returns (address);
/// Returns a delegator info
/// @param addr is the address to query
/// @return delegation is the address the addr delegated to
/// @return delegatorStake is the stake of the delegator as reflected in the delegation contract
function getDelegationInfo(address addr) external view returns (address delegation, uint256 delegatorStake);
/// Returns the delegated stake of an addr
/// @dev an address that is not self delegating has a 0 delegated stake
/// @param addr is the address to query
/// @return delegatedStake is the address delegated stake
function getDelegatedStake(address addr) external view returns (uint256);
/// Returns the total delegated stake
/// @dev delegatedStake - the total stake delegated to an address that is self delegating
/// @dev the delegated stake of a non self-delegated address is 0
/// @return totalDelegatedStake is the total delegatedStake of all the addresses
function getTotalDelegatedStake() external view returns (uint256) ;
/*
* Governance functions
*/
event DelegationsImported(address[] from, address indexed to);
event DelegationInitialized(address indexed from, address indexed to);
/// Imports delegations during initial migration
/// @dev initialization function called only by the initializationManager
/// @dev Does not update the Rewards or Election contracts
/// @dev assumes deactivated Rewards
/// @param from is a list of delegator addresses
/// @param to is the address the delegators delegate to
function importDelegations(address[] calldata from, address to) external /* onlyMigrationManager onlyDuringDelegationImport */;
/// Initializes the delegation of an address during initial migration
/// @dev initialization function called only by the initializationManager
/// @dev behaves identically to a delegate transaction sent by the delegator
/// @param from is the delegator addresses
/// @param to is the delegator delegates to
function initDelegation(address from, address to) external /* onlyInitializationAdmin */;
}
// File: contracts/IMigratableStakingContract.sol
pragma solidity 0.6.12;
/// @title An interface for staking contracts which support stake migration.
interface IMigratableStakingContract {
/// @dev Returns the address of the underlying staked token.
/// @return IERC20 The address of the token.
function getToken() external view returns (IERC20);
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _stakeOwner address The specified stake owner.
/// @param _amount uint256 The number of tokens to stake.
function acceptMigration(address _stakeOwner, uint256 _amount) external;
event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
}
// File: contracts/IStakingContract.sol
pragma solidity 0.6.12;
/// @title An interface for staking contracts.
interface IStakingContract {
/// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _amount uint256 The amount of tokens to stake.
function stake(uint256 _amount) external;
/// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which
/// msg.sender would be able to withdraw all of his tokens.
/// @param _amount uint256 The amount of tokens to unstake.
function unstake(uint256 _amount) external;
/// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS
/// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was
/// requested to release all stakes).
function withdraw() external;
/// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender.
function restake() external;
/// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method
/// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a
/// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that
/// callers will be able to properly batch/paginate their requests.
/// @param _totalAmount uint256 The total amount of rewards to distribute.
/// @param _stakeOwners address[] The addresses of the stake owners.
/// @param _amounts uint256[] The amounts of the rewards.
function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external;
/// @dev Returns the stake of the specified stake owner (excluding unstaked tokens).
/// @param _stakeOwner address The address to check.
/// @return uint256 The total stake.
function getStakeBalanceOf(address _stakeOwner) external view returns (uint256);
/// @dev Returns the total amount staked tokens (excluding unstaked tokens).
/// @return uint256 The total staked tokens of all stake owners.
function getTotalStakedTokens() external view returns (uint256);
/// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released.
/// @param _stakeOwner address The address to check.
/// @return cooldownAmount uint256 The total tokens in cooldown.
/// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds).
function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount,
uint256 cooldownEndTime);
/// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract.
/// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration.
/// @param _amount uint256 The amount of tokens to migrate.
function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external;
event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount);
}
// File: contracts/spec_interfaces/IManagedContract.sol
pragma solidity 0.6.12;
/// @title managed contract interface, used by the contracts registry to notify the contract on updates
interface IManagedContract /* is ILockable, IContractRegistryAccessor, Initializable */ {
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() external;
}
// File: contracts/spec_interfaces/IContractRegistry.sol
pragma solidity 0.6.12;
/// @title Contract registry contract interface
/// @dev The contract registry holds Orbs PoS contracts and managers lists
/// @dev The contract registry updates the managed contracts on changes in the contract list
/// @dev Governance functions restricted to managers access the registry to retrieve the manager address
/// @dev The contract registry represents the source of truth for Orbs Ethereum contracts
/// @dev By tracking the registry events or query before interaction, one can access the up to date contracts
interface IContractRegistry {
event ContractAddressUpdated(string contractName, address addr, bool managedContract);
event ManagerChanged(string role, address newManager);
event ContractRegistryUpdated(address newContractRegistry);
/*
* External functions
*/
/// Updates the contracts address and emits a corresponding event
/// @dev governance function called only by the migrationManager or registryAdmin
/// @param contractName is the contract name, used to identify it
/// @param addr is the contract updated address
/// @param managedContract indicates whether the contract is managed by the registry and notified on changes
function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdminOrMigrationManager */;
/// Returns the current address of the given contracts
/// @param contractName is the contract name, used to identify it
/// @return addr is the contract updated address
function getContract(string calldata contractName) external view returns (address);
/// Returns the list of contract addresses managed by the registry
/// @dev Managed contracts are updated on changes in the registry contracts addresses
/// @return addrs is the list of managed contracts
function getManagedContracts() external view returns (address[] memory);
/// Locks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
/// @dev When set all onlyWhenActive functions will revert
function lockContracts() external /* onlyAdminOrMigrationManager */;
/// Unlocks all the managed contracts
/// @dev governance function called only by the migrationManager or registryAdmin
function unlockContracts() external /* onlyAdminOrMigrationManager */;
/// Updates a manager address and emits a corresponding event
/// @dev governance function called only by the registryAdmin
/// @dev the managers list is a flexible list of role to the manager's address
/// @param role is the managers' role name, for example "functionalManager"
/// @param manager is the manager updated address
function setManager(string calldata role, address manager) external /* onlyAdmin */;
/// Returns the current address of the given manager
/// @param role is the manager name, used to identify it
/// @return addr is the manager updated address
function getManager(string calldata role) external view returns (address);
/// Sets a new contract registry to migrate to
/// @dev governance function called only by the registryAdmin
/// @dev updates the registry address record in all the managed contracts
/// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts
/// @param newRegistry is the new registry contract
function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */;
/// Returns the previous contract registry address
/// @dev used when the setting the contract as a new registry to assure a valid registry
/// @return previousContractRegistry is the previous contract registry
function getPreviousContractRegistry() external view returns (address);
}
// File: contracts/spec_interfaces/IContractRegistryAccessor.sol
pragma solidity 0.6.12;
interface IContractRegistryAccessor {
/// Sets the contract registry address
/// @dev governance function called only by an admin
/// @param newRegistry is the new registry contract
function setContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */;
/// Returns the contract registry address
/// @return contractRegistry is the contract registry address
function getContractRegistry() external view returns (IContractRegistry contractRegistry);
function setRegistryAdmin(address _registryAdmin) external /* onlyInitializationAdmin */;
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/WithClaimableRegistryManagement.sol
pragma solidity 0.6.12;
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract WithClaimableRegistryManagement is Context {
address private _registryAdmin;
address private _pendingRegistryAdmin;
event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin);
/**
* @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin.
*/
constructor () internal {
address msgSender = _msgSender();
_registryAdmin = msgSender;
emit RegistryManagementTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current registryAdmin.
*/
function registryAdmin() public view returns (address) {
return _registryAdmin;
}
/**
* @dev Throws if called by any account other than the registryAdmin.
*/
modifier onlyRegistryAdmin() {
require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin");
_;
}
/**
* @dev Returns true if the caller is the current registryAdmin.
*/
function isRegistryAdmin() public view returns (bool) {
return _msgSender() == _registryAdmin;
}
/**
* @dev Leaves the contract without registryAdmin. It will not be possible to call
* `onlyManager` functions anymore. Can only be called by the current registryAdmin.
*
* NOTE: Renouncing registryManagement will leave the contract without an registryAdmin,
* thereby removing any functionality that is only available to the registryAdmin.
*/
function renounceRegistryManagement() public onlyRegistryAdmin {
emit RegistryManagementTransferred(_registryAdmin, address(0));
_registryAdmin = address(0);
}
/**
* @dev Transfers registryManagement of the contract to a new account (`newManager`).
*/
function _transferRegistryManagement(address newRegistryAdmin) internal {
require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address");
emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin);
_registryAdmin = newRegistryAdmin;
}
/**
* @dev Modifier throws if called by any account other than the pendingManager.
*/
modifier onlyPendingRegistryAdmin() {
require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin");
_;
}
/**
* @dev Allows the current registryAdmin to set the pendingManager address.
* @param newRegistryAdmin The address to transfer registryManagement to.
*/
function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin {
_pendingRegistryAdmin = newRegistryAdmin;
}
/**
* @dev Allows the _pendingRegistryAdmin address to finalize the transfer.
*/
function claimRegistryManagement() external onlyPendingRegistryAdmin {
_transferRegistryManagement(_pendingRegistryAdmin);
_pendingRegistryAdmin = address(0);
}
/**
* @dev Returns the current pendingRegistryAdmin
*/
function pendingRegistryAdmin() public view returns (address) {
return _pendingRegistryAdmin;
}
}
// File: contracts/Initializable.sol
pragma solidity 0.6.12;
contract Initializable {
address private _initializationAdmin;
event InitializationComplete();
/// Constructor
/// Sets the initializationAdmin to the contract deployer
/// The initialization admin may call any manager only function until initializationComplete
constructor() public{
_initializationAdmin = msg.sender;
}
modifier onlyInitializationAdmin() {
require(msg.sender == initializationAdmin(), "sender is not the initialization admin");
_;
}
/*
* External functions
*/
/// Returns the initializationAdmin address
function initializationAdmin() public view returns (address) {
return _initializationAdmin;
}
/// Finalizes the initialization and revokes the initializationAdmin role
function initializationComplete() external onlyInitializationAdmin {
_initializationAdmin = address(0);
emit InitializationComplete();
}
/// Checks if the initialization was completed
function isInitializationComplete() public view returns (bool) {
return _initializationAdmin == address(0);
}
}
// File: contracts/ContractRegistryAccessor.sol
pragma solidity 0.6.12;
contract ContractRegistryAccessor is IContractRegistryAccessor, WithClaimableRegistryManagement, Initializable {
IContractRegistry private contractRegistry;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) public {
require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0");
setContractRegistry(_contractRegistry);
_transferRegistryManagement(_registryAdmin);
}
modifier onlyAdmin {
require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)");
_;
}
modifier onlyMigrationManager {
require(isMigrationManager(), "sender is not the migration manager");
_;
}
modifier onlyFunctionalManager {
require(isFunctionalManager(), "sender is not the functional manager");
_;
}
/// Checks whether the caller is Admin: either the contract registry, the registry admin, or the initialization admin
function isAdmin() internal view returns (bool) {
return msg.sender == address(contractRegistry) || msg.sender == registryAdmin() || msg.sender == initializationAdmin();
}
/// Checks whether the caller is a specific manager role or and Admin
/// @dev queries the registry contract for the up to date manager assignment
function isManager(string memory role) internal view returns (bool) {
IContractRegistry _contractRegistry = contractRegistry;
return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender;
}
/// Checks whether the caller is the migration manager
function isMigrationManager() internal view returns (bool) {
return isManager('migrationManager');
}
/// Checks whether the caller is the functional manager
function isFunctionalManager() internal view returns (bool) {
return isManager('functionalManager');
}
/*
* Contract getters, return the address of a contract by calling the contract registry
*/
function getProtocolContract() internal view returns (address) {
return contractRegistry.getContract("protocol");
}
function getStakingRewardsContract() internal view returns (address) {
return contractRegistry.getContract("stakingRewards");
}
function getFeesAndBootstrapRewardsContract() internal view returns (address) {
return contractRegistry.getContract("feesAndBootstrapRewards");
}
function getCommitteeContract() internal view returns (address) {
return contractRegistry.getContract("committee");
}
function getElectionsContract() internal view returns (address) {
return contractRegistry.getContract("elections");
}
function getDelegationsContract() internal view returns (address) {
return contractRegistry.getContract("delegations");
}
function getGuardiansRegistrationContract() internal view returns (address) {
return contractRegistry.getContract("guardiansRegistration");
}
function getCertificationContract() internal view returns (address) {
return contractRegistry.getContract("certification");
}
function getStakingContract() internal view returns (address) {
return contractRegistry.getContract("staking");
}
function getSubscriptionsContract() internal view returns (address) {
return contractRegistry.getContract("subscriptions");
}
function getStakingRewardsWallet() internal view returns (address) {
return contractRegistry.getContract("stakingRewardsWallet");
}
function getBootstrapRewardsWallet() internal view returns (address) {
return contractRegistry.getContract("bootstrapRewardsWallet");
}
function getGeneralFeesWallet() internal view returns (address) {
return contractRegistry.getContract("generalFeesWallet");
}
function getCertifiedFeesWallet() internal view returns (address) {
return contractRegistry.getContract("certifiedFeesWallet");
}
function getStakingContractHandler() internal view returns (address) {
return contractRegistry.getContract("stakingContractHandler");
}
/*
* Governance functions
*/
event ContractRegistryAddressUpdated(address addr);
/// Sets the contract registry address
/// @dev governance function called only by an admin
/// @param newContractRegistry is the new registry contract
function setContractRegistry(IContractRegistry newContractRegistry) public override onlyAdmin {
require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry");
contractRegistry = newContractRegistry;
emit ContractRegistryAddressUpdated(address(newContractRegistry));
}
/// Returns the contract registry that the contract is set to use
/// @return contractRegistry is the registry contract address
function getContractRegistry() public override view returns (IContractRegistry) {
return contractRegistry;
}
function setRegistryAdmin(address _registryAdmin) external override onlyInitializationAdmin {
_transferRegistryManagement(_registryAdmin);
}
}
// File: contracts/spec_interfaces/ILockable.sol
pragma solidity 0.6.12;
/// @title lockable contract interface, allows to lock a contract
interface ILockable {
event Locked();
event Unlocked();
/// Locks the contract to external non-governance function calls
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon locking all managed contracts
/// @dev getters and migration functions remain active also for locked contracts
/// @dev checked by the onlyWhenActive modifier
function lock() external /* onlyMigrationManager */;
/// Unlocks the contract
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon unlocking all managed contracts
function unlock() external /* onlyMigrationManager */;
/// Returns the contract locking status
/// @return isLocked is a bool indicating the contract is locked
function isLocked() view external returns (bool);
}
// File: contracts/Lockable.sol
pragma solidity 0.6.12;
/// @title lockable contract
contract Lockable is ILockable, ContractRegistryAccessor {
bool public locked;
/// Constructor
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {}
/// Locks the contract to external non-governance function calls
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon locking all managed contracts
/// @dev getters and migration functions remain active also for locked contracts
/// @dev checked by the onlyWhenActive modifier
function lock() external override onlyMigrationManager {
locked = true;
emit Locked();
}
/// Unlocks the contract
/// @dev governance function called only by the migration manager or an admin
/// @dev typically called by the registry contract upon unlocking all managed contracts
function unlock() external override onlyMigrationManager {
locked = false;
emit Unlocked();
}
/// Returns the contract locking status
/// @return isLocked is a bool indicating the contract is locked
function isLocked() external override view returns (bool) {
return locked;
}
modifier onlyWhenActive() {
require(!locked, "contract is locked for this operation");
_;
}
}
// File: contracts/ManagedContract.sol
pragma solidity 0.6.12;
/// @title managed contract
contract ManagedContract is IManagedContract, Lockable {
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {}
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() virtual override external {}
}
// File: contracts/StakingRewards.sol
pragma solidity 0.6.12;
contract StakingRewards is IStakingRewards, ManagedContract {
using SafeMath for uint256;
using SafeMath96 for uint96;
uint256 constant PERCENT_MILLIE_BASE = 100000;
uint256 constant TOKEN_BASE = 1e18;
struct Settings {
uint96 annualCap;
uint32 annualRateInPercentMille;
uint32 defaultDelegatorsStakingRewardsPercentMille;
uint32 maxDelegatorsStakingRewardsPercentMille;
bool rewardAllocationActive;
}
Settings settings;
IERC20 public token;
struct StakingRewardsState {
uint96 stakingRewardsPerWeight;
uint96 unclaimedStakingRewards;
uint32 lastAssigned;
}
StakingRewardsState public stakingRewardsState;
uint256 public stakingRewardsContractBalance;
struct GuardianStakingRewards {
uint96 delegatorRewardsPerToken;
uint96 lastStakingRewardsPerWeight;
uint96 balance;
uint96 claimed;
}
mapping(address => GuardianStakingRewards) public guardiansStakingRewards;
struct GuardianRewardSettings {
uint32 delegatorsStakingRewardsPercentMille;
bool overrideDefault;
}
mapping(address => GuardianRewardSettings) public guardiansRewardSettings;
struct DelegatorStakingRewards {
uint96 balance;
uint96 lastDelegatorRewardsPerToken;
uint96 claimed;
}
mapping(address => DelegatorStakingRewards) public delegatorsStakingRewards;
/// Constructor
/// @dev the constructor does not migrate reward balances from the previous rewards contract
/// @param _contractRegistry is the contract registry address
/// @param _registryAdmin is the registry admin address
/// @param _token is the token used for staking rewards
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
/// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille)
/// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000)
/// @param previousRewardsContract is the previous rewards contract address used for migration of guardians settings. address(0) indicates no guardian settings to migrate
/// @param guardiansToMigrate is a list of guardian addresses to migrate their rewards settings
constructor(
IContractRegistry _contractRegistry,
address _registryAdmin,
IERC20 _token,
uint32 annualRateInPercentMille,
uint96 annualCap,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
IStakingRewards previousRewardsContract,
address[] memory guardiansToMigrate
) ManagedContract(_contractRegistry, _registryAdmin) public {
require(address(_token) != address(0), "token must not be 0");
_setAnnualStakingRewardsRate(annualRateInPercentMille, annualCap);
setMaxDelegatorsStakingRewardsPercentMille(maxDelegatorsStakingRewardsPercentMille);
setDefaultDelegatorsStakingRewardsPercentMille(defaultDelegatorsStakingRewardsPercentMille);
token = _token;
if (address(previousRewardsContract) != address(0)) {
migrateGuardiansSettings(previousRewardsContract, guardiansToMigrate);
}
}
modifier onlyCommitteeContract() {
require(msg.sender == address(committeeContract), "caller is not the elections contract");
_;
}
modifier onlyDelegationsContract() {
require(msg.sender == address(delegationsContract), "caller is not the delegations contract");
_;
}
/*
* External functions
*/
/// Returns the current reward balance of the given address.
/// @dev calculates the up to date balances (differ from the state)
/// @param addr is the address to query
/// @return delegatorStakingRewardsBalance the rewards awarded to the guardian role
/// @return guardianStakingRewardsBalance the rewards awarded to the guardian role
function getStakingRewardsBalance(address addr) external override view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance) {
(DelegatorStakingRewards memory delegatorStakingRewards,,) = getDelegatorStakingRewards(addr, block.timestamp);
(GuardianStakingRewards memory guardianStakingRewards,,) = getGuardianStakingRewards(addr, block.timestamp);
return (delegatorStakingRewards.balance, guardianStakingRewards.balance);
}
/// Claims the staking rewards balance of an addr, staking the rewards
/// @dev Claimed rewards are staked in the staking contract using the distributeRewards interface
/// @dev includes the rewards for both the delegator and guardian roles
/// @dev calculates the up to date rewards prior to distribute them to the staking contract
/// @param addr is the address to claim rewards for
function claimStakingRewards(address addr) external override onlyWhenActive {
(uint256 guardianRewards, uint256 delegatorRewards) = claimStakingRewardsLocally(addr);
uint256 total = delegatorRewards.add(guardianRewards);
if (total == 0) {
return;
}
uint96 claimedGuardianRewards = guardiansStakingRewards[addr].claimed.add(guardianRewards);
guardiansStakingRewards[addr].claimed = claimedGuardianRewards;
uint96 claimedDelegatorRewards = delegatorsStakingRewards[addr].claimed.add(delegatorRewards);
delegatorsStakingRewards[addr].claimed = claimedDelegatorRewards;
require(token.approve(address(stakingContract), total), "claimStakingRewards: approve failed");
address[] memory addrs = new address[](1);
addrs[0] = addr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = total;
stakingContract.distributeRewards(total, addrs, amounts);
emit StakingRewardsClaimed(addr, delegatorRewards, guardianRewards, claimedDelegatorRewards, claimedGuardianRewards);
}
/// Returns the current global staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @return stakingRewardsPerWeight is the potential reward per 1E18 (TOKEN_BASE) committee weight assigned to a guardian was in the committee from day zero
/// @return unclaimedStakingRewards is the of tokens that were assigned to participants and not claimed yet
function getStakingRewardsState() public override view returns (
uint96 stakingRewardsPerWeight,
uint96 unclaimedStakingRewards
) {
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
(StakingRewardsState memory _stakingRewardsState,) = _getStakingRewardsState(totalCommitteeWeight, block.timestamp, settings);
stakingRewardsPerWeight = _stakingRewardsState.stakingRewardsPerWeight;
unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards;
}
/// Returns the current guardian staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @dev notice that the guardian rewards are the rewards for the guardian role as guardian and do not include delegation rewards
/// @dev use getDelegatorStakingRewardsData to get the guardian's rewards as delegator
/// @param guardian is the guardian to query
/// @return balance is the staking rewards balance for the guardian role
/// @return claimed is the staking rewards for the guardian role that were claimed
/// @return delegatorRewardsPerToken is the potential reward per token (1E18 units) assigned to a guardian's delegator that delegated from day zero
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last guardian update
/// @return lastStakingRewardsPerWeight is the up to date stakingRewardsPerWeight used for the guardian state calculation
/// @return stakingRewardsPerWeightDelta is the increment in stakingRewardsPerWeight since the last guardian update
function getGuardianStakingRewardsData(address guardian) external override view returns (
uint256 balance,
uint256 claimed,
uint256 delegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta,
uint256 lastStakingRewardsPerWeight,
uint256 stakingRewardsPerWeightDelta
) {
(GuardianStakingRewards memory rewards, uint256 _stakingRewardsPerWeightDelta, uint256 _delegatorRewardsPerTokenDelta) = getGuardianStakingRewards(guardian, block.timestamp);
return (rewards.balance, rewards.claimed, rewards.delegatorRewardsPerToken, _delegatorRewardsPerTokenDelta, rewards.lastStakingRewardsPerWeight, _stakingRewardsPerWeightDelta);
}
/// Returns the current delegator staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @param delegator is the delegator to query
/// @return balance is the staking rewards balance for the delegator role
/// @return claimed is the staking rewards for the delegator role that were claimed
/// @return guardian is the guardian the delegator delegated to receiving a portion of the guardian staking rewards
/// @return lastDelegatorRewardsPerToken is the up to date delegatorRewardsPerToken used for the delegator state calculation
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last delegator update
function getDelegatorStakingRewardsData(address delegator) external override view returns (
uint256 balance,
uint256 claimed,
address guardian,
uint256 lastDelegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta
) {
(DelegatorStakingRewards memory rewards, address _guardian, uint256 _delegatorRewardsPerTokenDelta) = getDelegatorStakingRewards(delegator, block.timestamp);
return (rewards.balance, rewards.claimed, _guardian, rewards.lastDelegatorRewardsPerToken, _delegatorRewardsPerTokenDelta);
}
/// Returns an estimation for the delegator and guardian staking rewards for a given duration
/// @dev the returned value is an estimation, assuming no change in the PoS state
/// @dev the period calculated for start from the current block time until the current time + duration.
/// @param addr is the address to estimate rewards for
/// @param duration is the duration to calculate for in seconds
/// @return estimatedDelegatorStakingRewards is the estimated reward for the delegator role
/// @return estimatedGuardianStakingRewards is the estimated reward for the guardian role
function estimateFutureRewards(address addr, uint256 duration) external override view returns (uint256 estimatedDelegatorStakingRewards, uint256 estimatedGuardianStakingRewards) {
(GuardianStakingRewards memory guardianRewardsNow,,) = getGuardianStakingRewards(addr, block.timestamp);
(DelegatorStakingRewards memory delegatorRewardsNow,,) = getDelegatorStakingRewards(addr, block.timestamp);
(GuardianStakingRewards memory guardianRewardsFuture,,) = getGuardianStakingRewards(addr, block.timestamp.add(duration));
(DelegatorStakingRewards memory delegatorRewardsFuture,,) = getDelegatorStakingRewards(addr, block.timestamp.add(duration));
estimatedDelegatorStakingRewards = delegatorRewardsFuture.balance.sub(delegatorRewardsNow.balance);
estimatedGuardianStakingRewards = guardianRewardsFuture.balance.sub(guardianRewardsNow.balance);
}
/// Sets the guardian's delegators staking reward portion
/// @dev by default uses the defaultDelegatorsStakingRewardsPercentMille
/// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille)
function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external override onlyWhenActive {
require(delegatorRewardsPercentMille <= PERCENT_MILLIE_BASE, "delegatorRewardsPercentMille must be 100000 at most");
require(delegatorRewardsPercentMille <= settings.maxDelegatorsStakingRewardsPercentMille, "delegatorRewardsPercentMille must not be larger than maxDelegatorsStakingRewardsPercentMille");
updateDelegatorStakingRewards(msg.sender);
_setGuardianDelegatorsStakingRewardsPercentMille(msg.sender, delegatorRewardsPercentMille);
}
/// Returns a guardian's delegators staking reward portion
/// @dev If not explicitly set, returns the defaultDelegatorsStakingRewardsPercentMille
/// @return delegatorRewardsRatioPercentMille is the delegators portion in percent-mille
function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external override view returns (uint256 delegatorRewardsRatioPercentMille) {
return _getGuardianDelegatorsStakingRewardsPercentMille(guardian, settings);
}
/// Returns the amount of ORBS tokens in the staking rewards wallet allocated to staking rewards
/// @dev The staking wallet balance must always larger than the allocated value
/// @return allocated is the amount of tokens allocated in the staking rewards wallet
function getStakingRewardsWalletAllocatedTokens() external override view returns (uint256 allocated) {
(, uint96 unclaimedStakingRewards) = getStakingRewardsState();
return uint256(unclaimedStakingRewards).sub(stakingRewardsContractBalance);
}
/// Returns the current annual staking reward rate
/// @dev calculated based on the current total committee weight
/// @return annualRate is the current staking reward rate in percent-mille
function getCurrentStakingRewardsRatePercentMille() external override view returns (uint256 annualRate) {
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
annualRate = _getAnnualRewardPerWeight(totalCommitteeWeight, settings).mul(PERCENT_MILLIE_BASE).div(TOKEN_BASE);
}
/// Notifies an expected change in the committee membership of the guardian
/// @dev Called only by: the Committee contract
/// @dev called upon expected change in the committee membership of the guardian
/// @dev triggers update of the global rewards state and the guardian rewards state
/// @dev updates the rewards state based on the committee state prior to the change
/// @param guardian is the guardian who's committee membership is updated
/// @param weight is the weight of the guardian prior to the change
/// @param totalCommitteeWeight is the total committee weight prior to the change
/// @param inCommittee indicates whether the guardian was in the committee prior to the change
/// @param inCommitteeAfter indicates whether the guardian is in the committee after the change
function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external override onlyWhenActive onlyCommitteeContract {
uint256 delegatedStake = delegationsContract.getDelegatedStake(guardian);
Settings memory _settings = settings;
StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings);
_updateGuardianStakingRewards(guardian, inCommittee, inCommitteeAfter, weight, delegatedStake, _stakingRewardsState, _settings);
}
/// Notifies an expected change in a delegator and his guardian delegation state
/// @dev Called only by: the Delegation contract
/// @dev called upon expected change in a delegator's delegation state
/// @dev triggers update of the global rewards state, the guardian rewards state and the delegator rewards state
/// @dev on delegation change, updates also the new guardian and the delegator's lastDelegatorRewardsPerToken accordingly
/// @param guardian is the delegator's guardian prior to the change
/// @param guardianDelegatedStake is the delegated stake of the delegator's guardian prior to the change
/// @param delegator is the delegator about to change delegation state
/// @param delegatorStake is the stake of the delegator
/// @param nextGuardian is the delegator's guardian after to the change
/// @param nextGuardianDelegatedStake is the delegated stake of the delegator's guardian after to the change
function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external override onlyWhenActive onlyDelegationsContract {
Settings memory _settings = settings;
(bool inCommittee, uint256 weight, , uint256 totalCommitteeWeight) = committeeContract.getMemberInfo(guardian);
StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings);
GuardianStakingRewards memory guardianStakingRewards = _updateGuardianStakingRewards(guardian, inCommittee, inCommittee, weight, guardianDelegatedStake, _stakingRewardsState, _settings);
_updateDelegatorStakingRewards(delegator, delegatorStake, guardian, guardianStakingRewards);
if (nextGuardian != guardian) {
(inCommittee, weight, , totalCommitteeWeight) = committeeContract.getMemberInfo(nextGuardian);
GuardianStakingRewards memory nextGuardianStakingRewards = _updateGuardianStakingRewards(nextGuardian, inCommittee, inCommittee, weight, nextGuardianDelegatedStake, _stakingRewardsState, _settings);
delegatorsStakingRewards[delegator].lastDelegatorRewardsPerToken = nextGuardianStakingRewards.delegatorRewardsPerToken;
}
}
/*
* Governance functions
*/
/// Activates staking rewards allocation
/// @dev governance function called only by the initialization admin
/// @dev On migrations, startTime should be set to the previous contract deactivation time
/// @param startTime sets the last assignment time
function activateRewardDistribution(uint startTime) external override onlyMigrationManager {
require(!settings.rewardAllocationActive, "reward distribution is already activated");
stakingRewardsState.lastAssigned = uint32(startTime);
settings.rewardAllocationActive = true;
emit RewardDistributionActivated(startTime);
}
/// Deactivates fees and bootstrap allocation
/// @dev governance function called only by the migration manager
/// @dev guardians updates remain active based on the current perMember value
function deactivateRewardDistribution() external override onlyMigrationManager {
require(settings.rewardAllocationActive, "reward distribution is already deactivated");
StakingRewardsState memory _stakingRewardsState = updateStakingRewardsState();
settings.rewardAllocationActive = false;
withdrawRewardsWalletAllocatedTokens(_stakingRewardsState);
emit RewardDistributionDeactivated();
}
/// Sets the default delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille)
function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) public override onlyFunctionalManager {
require(defaultDelegatorsStakingRewardsPercentMille <= PERCENT_MILLIE_BASE, "defaultDelegatorsStakingRewardsPercentMille must not be larger than 100000");
require(defaultDelegatorsStakingRewardsPercentMille <= settings.maxDelegatorsStakingRewardsPercentMille, "defaultDelegatorsStakingRewardsPercentMille must not be larger than maxDelegatorsStakingRewardsPercentMille");
settings.defaultDelegatorsStakingRewardsPercentMille = defaultDelegatorsStakingRewardsPercentMille;
emit DefaultDelegatorsStakingRewardsChanged(defaultDelegatorsStakingRewardsPercentMille);
}
/// Returns the default delegators staking reward portion
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
function getDefaultDelegatorsStakingRewardsPercentMille() public override view returns (uint32) {
return settings.defaultDelegatorsStakingRewardsPercentMille;
}
/// Sets the maximum delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000)
function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) public override onlyFunctionalManager {
require(maxDelegatorsStakingRewardsPercentMille <= PERCENT_MILLIE_BASE, "maxDelegatorsStakingRewardsPercentMille must not be larger than 100000");
settings.maxDelegatorsStakingRewardsPercentMille = maxDelegatorsStakingRewardsPercentMille;
emit MaxDelegatorsStakingRewardsChanged(maxDelegatorsStakingRewardsPercentMille);
}
/// Returns the default delegators staking reward portion
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
function getMaxDelegatorsStakingRewardsPercentMille() public override view returns (uint32) {
return settings.maxDelegatorsStakingRewardsPercentMille;
}
/// Sets the annual rate and cap for the staking reward
/// @dev governance function called only by the functional manager
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external override onlyFunctionalManager {
updateStakingRewardsState();
return _setAnnualStakingRewardsRate(annualRateInPercentMille, annualCap);
}
/// Returns the annual staking reward rate
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
function getAnnualStakingRewardsRatePercentMille() external override view returns (uint32) {
return settings.annualRateInPercentMille;
}
/// Returns the annual staking rewards cap
/// @return annualStakingRewardsCap is the annual rate in percent-mille
function getAnnualStakingRewardsCap() external override view returns (uint256) {
return settings.annualCap;
}
/// Checks if rewards allocation is active
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function isRewardAllocationActive() external override view returns (bool) {
return settings.rewardAllocationActive;
}
/// Returns the contract's settings
/// @return annualStakingRewardsCap is the annual rate in percent-mille
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function getSettings() external override view returns (
uint annualStakingRewardsCap,
uint32 annualStakingRewardsRatePercentMille,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
bool rewardAllocationActive
) {
Settings memory _settings = settings;
annualStakingRewardsCap = _settings.annualCap;
annualStakingRewardsRatePercentMille = _settings.annualRateInPercentMille;
defaultDelegatorsStakingRewardsPercentMille = _settings.defaultDelegatorsStakingRewardsPercentMille;
maxDelegatorsStakingRewardsPercentMille = _settings.maxDelegatorsStakingRewardsPercentMille;
rewardAllocationActive = _settings.rewardAllocationActive;
}
/// Migrates the staking rewards balance of the given addresses to a new staking rewards contract
/// @dev The new rewards contract is determined according to the contracts registry
/// @dev No impact of the calling contract if the currently configured contract in the registry
/// @dev may be called also while the contract is locked
/// @param addrs is the list of addresses to migrate
function migrateRewardsBalance(address[] calldata addrs) external override {
require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration");
IStakingRewards currentRewardsContract = IStakingRewards(getStakingRewardsContract());
require(address(currentRewardsContract) != address(this), "New rewards contract is not set");
uint256 totalAmount = 0;
uint256[] memory guardianRewards = new uint256[](addrs.length);
uint256[] memory delegatorRewards = new uint256[](addrs.length);
for (uint i = 0; i < addrs.length; i++) {
(guardianRewards[i], delegatorRewards[i]) = claimStakingRewardsLocally(addrs[i]);
totalAmount = totalAmount.add(guardianRewards[i]).add(delegatorRewards[i]);
}
require(token.approve(address(currentRewardsContract), totalAmount), "migrateRewardsBalance: approve failed");
currentRewardsContract.acceptRewardsBalanceMigration(addrs, guardianRewards, delegatorRewards, totalAmount);
for (uint i = 0; i < addrs.length; i++) {
emit StakingRewardsBalanceMigrated(addrs[i], guardianRewards[i], delegatorRewards[i], address(currentRewardsContract));
}
}
/// Accepts addresses balance migration from a previous rewards contract
/// @dev the function may be called by any caller that approves the amounts provided for transfer
/// @param addrs is the list migrated addresses
/// @param migratedGuardianStakingRewards is the list of received guardian rewards balance for each address
/// @param migratedDelegatorStakingRewards is the list of received delegator rewards balance for each address
/// @param totalAmount is the total amount of staking rewards migrated for all addresses in the list. Must match the sum of migratedGuardianStakingRewards and migratedDelegatorStakingRewards lists.
function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external override {
uint256 _totalAmount = 0;
for (uint i = 0; i < addrs.length; i++) {
_totalAmount = _totalAmount.add(migratedGuardianStakingRewards[i]).add(migratedDelegatorStakingRewards[i]);
}
require(totalAmount == _totalAmount, "totalAmount does not match sum of rewards");
if (totalAmount > 0) {
require(token.transferFrom(msg.sender, address(this), totalAmount), "acceptRewardBalanceMigration: transfer failed");
}
for (uint i = 0; i < addrs.length; i++) {
guardiansStakingRewards[addrs[i]].balance = guardiansStakingRewards[addrs[i]].balance.add(migratedGuardianStakingRewards[i]);
delegatorsStakingRewards[addrs[i]].balance = delegatorsStakingRewards[addrs[i]].balance.add(migratedDelegatorStakingRewards[i]);
emit StakingRewardsBalanceMigrationAccepted(msg.sender, addrs[i], migratedGuardianStakingRewards[i], migratedDelegatorStakingRewards[i]);
}
stakingRewardsContractBalance = stakingRewardsContractBalance.add(totalAmount);
stakingRewardsState.unclaimedStakingRewards = stakingRewardsState.unclaimedStakingRewards.add(totalAmount);
}
/// Performs emergency withdrawal of the contract balance
/// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens
/// @dev governance function called only by the migration manager
/// @param erc20 is the ERC20 token to withdraw
function emergencyWithdraw(address erc20) external override onlyMigrationManager {
IERC20 _token = IERC20(erc20);
emit EmergencyWithdrawal(msg.sender, address(_token));
require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "StakingRewards::emergencyWithdraw - transfer failed");
}
/*
* Private functions
*/
// Global state
/// Returns the annual reward per weight
/// @dev calculates the current annual rewards per weight based on the annual rate and annual cap
function _getAnnualRewardPerWeight(uint256 totalCommitteeWeight, Settings memory _settings) private pure returns (uint256) {
return totalCommitteeWeight == 0 ? 0 : Math.min(uint256(_settings.annualRateInPercentMille).mul(TOKEN_BASE).div(PERCENT_MILLIE_BASE), uint256(_settings.annualCap).mul(TOKEN_BASE).div(totalCommitteeWeight));
}
/// Calculates the added rewards per weight for the given duration based on the committee data
/// @param totalCommitteeWeight is the current committee total weight
/// @param duration is the duration to calculate for in seconds
/// @param _settings is the contract settings
function calcStakingRewardPerWeightDelta(uint256 totalCommitteeWeight, uint duration, Settings memory _settings) private pure returns (uint256 stakingRewardsPerWeightDelta) {
stakingRewardsPerWeightDelta = 0;
if (totalCommitteeWeight > 0) {
uint annualRewardPerWeight = _getAnnualRewardPerWeight(totalCommitteeWeight, _settings);
stakingRewardsPerWeightDelta = annualRewardPerWeight.mul(duration).div(365 days);
}
}
/// Returns the up global staking rewards state for a specific time
/// @dev receives the relevant committee data
/// @dev for future time calculations assumes no change in the committee data
/// @param totalCommitteeWeight is the current committee total weight
/// @param currentTime is the time to calculate the rewards for
/// @param _settings is the contract settings
function _getStakingRewardsState(uint256 totalCommitteeWeight, uint256 currentTime, Settings memory _settings) private view returns (StakingRewardsState memory _stakingRewardsState, uint256 allocatedRewards) {
_stakingRewardsState = stakingRewardsState;
if (_settings.rewardAllocationActive) {
uint delta = calcStakingRewardPerWeightDelta(totalCommitteeWeight, currentTime.sub(stakingRewardsState.lastAssigned), _settings);
_stakingRewardsState.stakingRewardsPerWeight = stakingRewardsState.stakingRewardsPerWeight.add(delta);
_stakingRewardsState.lastAssigned = uint32(currentTime);
allocatedRewards = delta.mul(totalCommitteeWeight).div(TOKEN_BASE);
_stakingRewardsState.unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards.add(allocatedRewards);
}
}
/// Updates the global staking rewards
/// @dev calculated to the latest block, may differ from the state read
/// @dev uses the _getStakingRewardsState function
/// @param totalCommitteeWeight is the current committee total weight
/// @param _settings is the contract settings
/// @return _stakingRewardsState is the updated global staking rewards struct
function _updateStakingRewardsState(uint256 totalCommitteeWeight, Settings memory _settings) private returns (StakingRewardsState memory _stakingRewardsState) {
if (!_settings.rewardAllocationActive) {
return stakingRewardsState;
}
uint allocatedRewards;
(_stakingRewardsState, allocatedRewards) = _getStakingRewardsState(totalCommitteeWeight, block.timestamp, _settings);
stakingRewardsState = _stakingRewardsState;
emit StakingRewardsAllocated(allocatedRewards, _stakingRewardsState.stakingRewardsPerWeight);
}
/// Updates the global staking rewards
/// @dev calculated to the latest block, may differ from the state read
/// @dev queries the committee state from the committee contract
/// @dev uses the _updateStakingRewardsState function
/// @return _stakingRewardsState is the updated global staking rewards struct
function updateStakingRewardsState() private returns (StakingRewardsState memory _stakingRewardsState) {
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
return _updateStakingRewardsState(totalCommitteeWeight, settings);
}
// Guardian state
/// Returns the current guardian staking rewards state
/// @dev receives the relevant committee and guardian data along with the global updated global state
/// @dev calculated to the latest block, may differ from the state read
/// @param guardian is the guardian to query
/// @param inCommittee indicates whether the guardian is currently in the committee
/// @param inCommitteeAfter indicates whether after a potential change the guardian is in the committee
/// @param guardianWeight is the guardian committee weight
/// @param guardianDelegatedStake is the guardian delegated stake
/// @param _stakingRewardsState is the updated global staking rewards state
/// @param _settings is the contract settings
/// @return guardianStakingRewards is the updated guardian staking rewards state
/// @return rewardsAdded is the amount awarded to the guardian since the last update
/// @return stakingRewardsPerWeightDelta is the delta added to the stakingRewardsPerWeight since the last update
/// @return delegatorRewardsPerTokenDelta is the delta added to the guardian's delegatorRewardsPerToken since the last update
function _getGuardianStakingRewards(address guardian, bool inCommittee, bool inCommitteeAfter, uint256 guardianWeight, uint256 guardianDelegatedStake, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private view returns (GuardianStakingRewards memory guardianStakingRewards, uint256 rewardsAdded, uint256 stakingRewardsPerWeightDelta, uint256 delegatorRewardsPerTokenDelta) {
guardianStakingRewards = guardiansStakingRewards[guardian];
if (inCommittee) {
stakingRewardsPerWeightDelta = uint256(_stakingRewardsState.stakingRewardsPerWeight).sub(guardianStakingRewards.lastStakingRewardsPerWeight);
uint256 totalRewards = stakingRewardsPerWeightDelta.mul(guardianWeight);
uint256 delegatorRewardsRatioPercentMille = _getGuardianDelegatorsStakingRewardsPercentMille(guardian, _settings);
delegatorRewardsPerTokenDelta = guardianDelegatedStake == 0 ? 0 : totalRewards
.div(guardianDelegatedStake)
.mul(delegatorRewardsRatioPercentMille)
.div(PERCENT_MILLIE_BASE);
uint256 guardianCutPercentMille = PERCENT_MILLIE_BASE.sub(delegatorRewardsRatioPercentMille);
rewardsAdded = totalRewards
.mul(guardianCutPercentMille)
.div(PERCENT_MILLIE_BASE)
.div(TOKEN_BASE);
guardianStakingRewards.delegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken.add(delegatorRewardsPerTokenDelta);
guardianStakingRewards.balance = guardianStakingRewards.balance.add(rewardsAdded);
}
guardianStakingRewards.lastStakingRewardsPerWeight = inCommitteeAfter ? _stakingRewardsState.stakingRewardsPerWeight : 0;
}
/// Returns the guardian staking rewards state for a given time
/// @dev if the time to estimate is in the future, estimates the rewards for the given time
/// @dev for future time estimation assumes no change in the committee and the guardian state
/// @param guardian is the guardian to query
/// @param currentTime is the time to calculate the rewards for
/// @return guardianStakingRewards is the guardian staking rewards state updated to the give time
/// @return stakingRewardsPerWeightDelta is the delta added to the stakingRewardsPerWeight since the last update
/// @return delegatorRewardsPerTokenDelta is the delta added to the guardian's delegatorRewardsPerToken since the last update
function getGuardianStakingRewards(address guardian, uint256 currentTime) private view returns (GuardianStakingRewards memory guardianStakingRewards, uint256 stakingRewardsPerWeightDelta, uint256 delegatorRewardsPerTokenDelta) {
Settings memory _settings = settings;
(bool inCommittee, uint256 guardianWeight, ,uint256 totalCommitteeWeight) = committeeContract.getMemberInfo(guardian);
uint256 guardianDelegatedStake = delegationsContract.getDelegatedStake(guardian);
(StakingRewardsState memory _stakingRewardsState,) = _getStakingRewardsState(totalCommitteeWeight, currentTime, _settings);
(guardianStakingRewards,,stakingRewardsPerWeightDelta,delegatorRewardsPerTokenDelta) = _getGuardianStakingRewards(guardian, inCommittee, inCommittee, guardianWeight, guardianDelegatedStake, _stakingRewardsState, _settings);
}
/// Updates a guardian staking rewards state
/// @dev receives the relevant committee and guardian data along with the global updated global state
/// @dev updates the global staking rewards state prior to calculating the guardian's
/// @dev uses _getGuardianStakingRewards
/// @param guardian is the guardian to update
/// @param inCommittee indicates whether the guardian was in the committee prior to the change
/// @param inCommitteeAfter indicates whether the guardian is in the committee after the change
/// @param guardianWeight is the committee weight of the guardian prior to the change
/// @param guardianDelegatedStake is the delegated stake of the guardian prior to the change
/// @param _stakingRewardsState is the updated global staking rewards state
/// @param _settings is the contract settings
/// @return guardianStakingRewards is the updated guardian staking rewards state
function _updateGuardianStakingRewards(address guardian, bool inCommittee, bool inCommitteeAfter, uint256 guardianWeight, uint256 guardianDelegatedStake, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private returns (GuardianStakingRewards memory guardianStakingRewards) {
uint256 guardianStakingRewardsAdded;
uint256 stakingRewardsPerWeightDelta;
uint256 delegatorRewardsPerTokenDelta;
(guardianStakingRewards, guardianStakingRewardsAdded, stakingRewardsPerWeightDelta, delegatorRewardsPerTokenDelta) = _getGuardianStakingRewards(guardian, inCommittee, inCommitteeAfter, guardianWeight, guardianDelegatedStake, _stakingRewardsState, _settings);
guardiansStakingRewards[guardian] = guardianStakingRewards;
emit GuardianStakingRewardsAssigned(guardian, guardianStakingRewardsAdded, guardianStakingRewards.claimed.add(guardianStakingRewards.balance), guardianStakingRewards.delegatorRewardsPerToken, delegatorRewardsPerTokenDelta, _stakingRewardsState.stakingRewardsPerWeight, stakingRewardsPerWeightDelta);
}
/// Updates a guardian staking rewards state
/// @dev queries the relevant guardian and committee data from the committee contract
/// @dev uses _updateGuardianStakingRewards
/// @param guardian is the guardian to update
/// @param _stakingRewardsState is the updated global staking rewards state
/// @param _settings is the contract settings
/// @return guardianStakingRewards is the updated guardian staking rewards state
function updateGuardianStakingRewards(address guardian, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private returns (GuardianStakingRewards memory guardianStakingRewards) {
(bool inCommittee, uint256 guardianWeight,,) = committeeContract.getMemberInfo(guardian);
return _updateGuardianStakingRewards(guardian, inCommittee, inCommittee, guardianWeight, delegationsContract.getDelegatedStake(guardian), _stakingRewardsState, _settings);
}
// Delegator state
/// Returns the current delegator staking rewards state
/// @dev receives the relevant delegator data along with the delegator's current guardian updated global state
/// @dev calculated to the latest block, may differ from the state read
/// @param delegator is the delegator to query
/// @param delegatorStake is the stake of the delegator
/// @param guardianStakingRewards is the updated guardian staking rewards state
/// @return delegatorStakingRewards is the updated delegator staking rewards state
/// @return delegatorRewardsAdded is the amount awarded to the delegator since the last update
/// @return delegatorRewardsPerTokenDelta is the delta added to the delegator's delegatorRewardsPerToken since the last update
function _getDelegatorStakingRewards(address delegator, uint256 delegatorStake, GuardianStakingRewards memory guardianStakingRewards) private view returns (DelegatorStakingRewards memory delegatorStakingRewards, uint256 delegatorRewardsAdded, uint256 delegatorRewardsPerTokenDelta) {
delegatorStakingRewards = delegatorsStakingRewards[delegator];
delegatorRewardsPerTokenDelta = uint256(guardianStakingRewards.delegatorRewardsPerToken)
.sub(delegatorStakingRewards.lastDelegatorRewardsPerToken);
delegatorRewardsAdded = delegatorRewardsPerTokenDelta
.mul(delegatorStake)
.div(TOKEN_BASE);
delegatorStakingRewards.balance = delegatorStakingRewards.balance.add(delegatorRewardsAdded);
delegatorStakingRewards.lastDelegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken;
}
/// Returns the delegator staking rewards state for a given time
/// @dev if the time to estimate is in the future, estimates the rewards for the given time
/// @dev for future time estimation assumes no change in the committee, delegation and the delegator state
/// @param delegator is the delegator to query
/// @param currentTime is the time to calculate the rewards for
/// @return delegatorStakingRewards is the updated delegator staking rewards state
/// @return guardian is the guardian the delegator delegated to
/// @return delegatorStakingRewardsPerTokenDelta is the delta added to the delegator's delegatorRewardsPerToken since the last update
function getDelegatorStakingRewards(address delegator, uint256 currentTime) private view returns (DelegatorStakingRewards memory delegatorStakingRewards, address guardian, uint256 delegatorStakingRewardsPerTokenDelta) {
uint256 delegatorStake;
(guardian, delegatorStake) = delegationsContract.getDelegationInfo(delegator);
(GuardianStakingRewards memory guardianStakingRewards,,) = getGuardianStakingRewards(guardian, currentTime);
(delegatorStakingRewards,,delegatorStakingRewardsPerTokenDelta) = _getDelegatorStakingRewards(delegator, delegatorStake, guardianStakingRewards);
}
/// Updates a delegator staking rewards state
/// @dev receives the relevant delegator data along with the delegator's current guardian updated global state
/// @dev updates the guardian staking rewards state prior to calculating the delegator's
/// @dev uses _getDelegatorStakingRewards
/// @param delegator is the delegator to update
/// @param delegatorStake is the stake of the delegator
/// @param guardianStakingRewards is the updated guardian staking rewards state
function _updateDelegatorStakingRewards(address delegator, uint256 delegatorStake, address guardian, GuardianStakingRewards memory guardianStakingRewards) private {
uint256 delegatorStakingRewardsAdded;
uint256 delegatorRewardsPerTokenDelta;
DelegatorStakingRewards memory delegatorStakingRewards;
(delegatorStakingRewards, delegatorStakingRewardsAdded, delegatorRewardsPerTokenDelta) = _getDelegatorStakingRewards(delegator, delegatorStake, guardianStakingRewards);
delegatorsStakingRewards[delegator] = delegatorStakingRewards;
emit DelegatorStakingRewardsAssigned(delegator, delegatorStakingRewardsAdded, delegatorStakingRewards.claimed.add(delegatorStakingRewards.balance), guardian, guardianStakingRewards.delegatorRewardsPerToken, delegatorRewardsPerTokenDelta);
}
/// Updates a delegator staking rewards state
/// @dev queries the relevant delegator and committee data from the committee contract and delegation contract
/// @dev uses _updateDelegatorStakingRewards
/// @param delegator is the delegator to update
function updateDelegatorStakingRewards(address delegator) private {
Settings memory _settings = settings;
(, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats();
StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings);
(address guardian, uint delegatorStake) = delegationsContract.getDelegationInfo(delegator);
GuardianStakingRewards memory guardianRewards = updateGuardianStakingRewards(guardian, _stakingRewardsState, _settings);
_updateDelegatorStakingRewards(delegator, delegatorStake, guardian, guardianRewards);
}
// Guardian settings
/// Returns the guardian's delegator portion in percent-mille
/// @dev if no explicit value was set by the guardian returns the default value
/// @dev enforces the maximum delegators staking rewards cut
function _getGuardianDelegatorsStakingRewardsPercentMille(address guardian, Settings memory _settings) private view returns (uint256 delegatorRewardsRatioPercentMille) {
GuardianRewardSettings memory guardianSettings = guardiansRewardSettings[guardian];
delegatorRewardsRatioPercentMille = guardianSettings.overrideDefault ? guardianSettings.delegatorsStakingRewardsPercentMille : _settings.defaultDelegatorsStakingRewardsPercentMille;
return Math.min(delegatorRewardsRatioPercentMille, _settings.maxDelegatorsStakingRewardsPercentMille);
}
/// Migrates a list of guardians' delegators portion setting from a previous staking rewards contract
/// @dev called by the constructor
function migrateGuardiansSettings(IStakingRewards previousRewardsContract, address[] memory guardiansToMigrate) private {
for (uint i = 0; i < guardiansToMigrate.length; i++) {
_setGuardianDelegatorsStakingRewardsPercentMille(guardiansToMigrate[i], uint32(previousRewardsContract.getGuardianDelegatorsStakingRewardsPercentMille(guardiansToMigrate[i])));
}
}
// Governance and misc.
/// Sets the annual rate and cap for the staking reward
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
function _setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) private {
Settings memory _settings = settings;
_settings.annualRateInPercentMille = annualRateInPercentMille;
_settings.annualCap = annualCap;
settings = _settings;
emit AnnualStakingRewardsRateChanged(annualRateInPercentMille, annualCap);
}
/// Sets the guardian's delegators staking reward portion
/// @param guardian is the guardian to set
/// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille)
function _setGuardianDelegatorsStakingRewardsPercentMille(address guardian, uint32 delegatorRewardsPercentMille) private {
guardiansRewardSettings[guardian] = GuardianRewardSettings({
overrideDefault: true,
delegatorsStakingRewardsPercentMille: delegatorRewardsPercentMille
});
emit GuardianDelegatorsStakingRewardsPercentMilleUpdated(guardian, delegatorRewardsPercentMille);
}
/// Claims an addr staking rewards and update its rewards state without transferring the rewards
/// @dev used by claimStakingRewards and migrateRewardsBalance
/// @param addr is the address to claim rewards for
/// @return guardianRewards is the claimed guardian rewards balance
/// @return delegatorRewards is the claimed delegator rewards balance
function claimStakingRewardsLocally(address addr) private returns (uint256 guardianRewards, uint256 delegatorRewards) {
updateDelegatorStakingRewards(addr);
guardianRewards = guardiansStakingRewards[addr].balance;
guardiansStakingRewards[addr].balance = 0;
delegatorRewards = delegatorsStakingRewards[addr].balance;
delegatorsStakingRewards[addr].balance = 0;
uint256 total = delegatorRewards.add(guardianRewards);
StakingRewardsState memory _stakingRewardsState = stakingRewardsState;
uint256 _stakingRewardsContractBalance = stakingRewardsContractBalance;
if (total > _stakingRewardsContractBalance) {
_stakingRewardsContractBalance = withdrawRewardsWalletAllocatedTokens(_stakingRewardsState);
}
stakingRewardsContractBalance = _stakingRewardsContractBalance.sub(total);
stakingRewardsState.unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards.sub(total);
}
/// Withdraws the tokens that were allocated to the contract from the staking rewards wallet
/// @dev used as part of the migration flow to withdraw all the funds allocated for participants before updating the wallet client to a new contract
/// @param _stakingRewardsState is the updated global staking rewards state
function withdrawRewardsWalletAllocatedTokens(StakingRewardsState memory _stakingRewardsState) private returns (uint256 _stakingRewardsContractBalance){
_stakingRewardsContractBalance = stakingRewardsContractBalance;
uint256 allocated = _stakingRewardsState.unclaimedStakingRewards.sub(_stakingRewardsContractBalance);
stakingRewardsWallet.withdraw(allocated);
_stakingRewardsContractBalance = _stakingRewardsContractBalance.add(allocated);
stakingRewardsContractBalance = _stakingRewardsContractBalance;
}
/*
* Contracts topology / registry interface
*/
ICommittee committeeContract;
IDelegations delegationsContract;
IProtocolWallet stakingRewardsWallet;
IStakingContract stakingContract;
/// Refreshes the address of the other contracts the contract interacts with
/// @dev called by the registry contract upon an update of a contract in the registry
function refreshContracts() external override {
committeeContract = ICommittee(getCommitteeContract());
delegationsContract = IDelegations(getDelegationsContract());
stakingRewardsWallet = IProtocolWallet(getStakingRewardsWallet());
stakingContract = IStakingContract(getStakingContract());
}
}
|
Updates the global staking rewards calculated to the latest block, may differ from the state read uses the _getStakingRewardsState function totalCommitteeWeight is the current committee total weight _settings is the contract settings return _stakingRewardsState is the updated global staking rewards struct
|
function _updateStakingRewardsState(uint256 totalCommitteeWeight, Settings memory _settings) private returns (StakingRewardsState memory _stakingRewardsState) {
if (!_settings.rewardAllocationActive) {
return stakingRewardsState;
}
uint allocatedRewards;
(_stakingRewardsState, allocatedRewards) = _getStakingRewardsState(totalCommitteeWeight, block.timestamp, _settings);
stakingRewardsState = _stakingRewardsState;
emit StakingRewardsAllocated(allocatedRewards, _stakingRewardsState.stakingRewardsPerWeight);
}
| 450,190 |
//Address: 0xecfad7325b812e45ed07e0dbc7ef3f98f13fb4f5
//Contract name: ProofShrimpFarmer
//Balance: 0 Ether
//Verification Date: 6/5/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.21; // solhint-disable-line
/*
* One Proof Shrimp Farm
* https://oneproof.net/games/shrimp
*
* Instead of having many small "proof of" smart contracts here you can
* create a unique website and use this same smart contract address.
* This would benefit all those holding because of the increased volume.
*
*
*
*
* One Proof Token Features:
* [✓] 5% rewards for token purchase, shared among all token holders.
* [✓] 5% rewards for token selling, shared among all token holders.
* [✓] 0% rewards for token transfer.
* [✓] 3% rewards is given to referrer which is 60% of the 5% purchase reward.
* [✓] Price increment by 0.000000001 instead of 0.00000001 for lower buy/sell price.
* [✓] 1 token to activate Masternode referrals.
* [✓] Ability to create games and other contracts that transact in One Proof Tokens.
* [✓] No Administrators or Ambassadors that can change anything with the contract.
*
*/
contract ERC20Interface {
function transfer(address to, uint256 tokens) public returns (bool success);
}
contract Proof {
function buy(address) public payable returns(uint256);
function transfer(address, uint256) public returns(bool);
function myTokens() public view returns(uint256);
function myDividends(bool) public view returns(uint256);
function reinvest() public;
}
/**
* Definition of contract accepting Proof tokens
* Games, casinos, anything can reuse this contract to support Proof tokens
*/
contract AcceptsProof {
Proof public tokenContract;
function AcceptsProof(address _tokenContract) public {
tokenContract = Proof(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 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, uint256 _value, bytes _data) external returns (bool);
}
// Seeded market of 8640000000 Eggs
contract ProofShrimpFarmer is AcceptsProof {
//uint256 EGGS_PER_SHRIMP_PER_SECOND=1;
uint256 public EGGS_TO_HATCH_1SHRIMP=86400;
uint256 public STARTING_SHRIMP=300;
uint256 PSN=10000;
uint256 PSNH=5000;
bool public initialized=true;
address public ceoAddress;
mapping (address => uint256) public hatcheryShrimp;
mapping (address => uint256) public claimedEggs;
mapping (address => uint256) public lastHatch;
mapping (address => address) public referrals;
uint256 public marketEggs=8640000000;
function ProofShrimpFarmer(address _baseContract)
AcceptsProof(_baseContract)
public{
ceoAddress=msg.sender;
}
/**
* Fallback function for the contract. Since this contract does not use ETH then don't accept it.
*/
function() payable public {
revert();
}
/**
* Deposit Proof tokens to buy eggs in farm
*
* @dev Standard ERC677 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, uint256 _value, bytes _data)
external
onlyTokenContract
returns (bool) {
require(initialized);
require(!_isContract(_from));
require(_value >= 1 finney); // 0.001 Proof token
uint256 ProofBalance = tokenContract.myTokens();
uint256 eggsBought=calculateEggBuy(_value, SafeMath.sub(ProofBalance, _value));
// This version does not have any devfees
// eggsBought=SafeMath.sub(eggsBought,devFee(eggsBought));
reinvest();
// tokenContract.transfer(ceoAddress, devFee(_value));
claimedEggs[_from]=SafeMath.add(claimedEggs[_from],eggsBought);
return true;
}
function hatchEggs(address ref) public{
require(initialized);
if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){
referrals[msg.sender]=ref;
}
uint256 eggsUsed=getMyEggs();
uint256 newShrimp=SafeMath.div(eggsUsed,EGGS_TO_HATCH_1SHRIMP);
hatcheryShrimp[msg.sender]=SafeMath.add(hatcheryShrimp[msg.sender],newShrimp);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
//send referral eggs
claimedEggs[referrals[msg.sender]]=SafeMath.add(claimedEggs[referrals[msg.sender]],SafeMath.div(eggsUsed,5));
//boost market to nerf shrimp hoarding
marketEggs=SafeMath.add(marketEggs,SafeMath.div(eggsUsed,10));
}
function sellEggs() public{
require(initialized);
uint256 hasEggs=getMyEggs();
uint256 eggValue=calculateEggSell(hasEggs);
// This version doesn't have devfees.
// uint256 fee=devFee(eggValue);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
marketEggs=SafeMath.add(marketEggs,hasEggs);
reinvest();
// no devFee
// tokenContract.transfer(ceoAddress, fee);
// tokenContract.transfer(msg.sender, SafeMath.sub(eggValue,fee));
tokenContract.transfer(msg.sender, eggValue);
}
// Dev should initially seed the game before start
function seedMarket(uint256 eggs) public {
require(msg.sender==ceoAddress); // only CEO can seed the market
initialized=true;
marketEggs=eggs;
}
// Reinvest Proof Shrimp Farm dividends
// All the dividends this contract makes will be used to grow token fund for players
// of the Proof Schrimp Farm
function reinvest() public {
if(tokenContract.myDividends(true) > 1) {
tokenContract.reinvest();
}
}
//magic trade balancing algorithm
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
//(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt));
return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt)));
}
// Calculate trade to sell eggs
function calculateEggSell(uint256 eggs) public view returns(uint256){
return calculateTrade(eggs,marketEggs, tokenContract.myTokens());
}
// Calculate trade to buy eggs
function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth, contractBalance, marketEggs);
}
// Calculate eggs to buy simple
function calculateEggBuySimple(uint256 eth) public view returns(uint256){
return calculateEggBuy(eth, tokenContract.myTokens());
}
// Calculate devfee in game
// This version doesn't use devFee
function devFee(uint256 amount) public pure returns(uint256){
return SafeMath.div(SafeMath.mul(amount,4),100);
}
// Get amount of Shrimps user has
function getMyShrimp() public view returns(uint256){
return hatcheryShrimp[msg.sender];
}
// Get amount of eggs of current user
function getMyEggs() public view returns(uint256){
return SafeMath.add(claimedEggs[msg.sender],getEggsSinceLastHatch(msg.sender));
}
// Get number of doges since last hatch
function getEggsSinceLastHatch(address adr) public view returns(uint256){
uint256 secondsPassed=min(EGGS_TO_HATCH_1SHRIMP,SafeMath.sub(now,lastHatch[adr]));
return SafeMath.mul(secondsPassed,hatcheryShrimp[adr]);
}
// Collect information about doge farm dividents amount
function getContractDividends() public view returns(uint256) {
return tokenContract.myDividends(true); // + this.balance;
}
// Get tokens balance of the doge farm
function getBalance() public view returns(uint256){
return tokenContract.myTokens();
}
// Check transaction coming from the contract or not
function _isContract(address _user) internal view returns (bool) {
uint size;
assembly { size := extcodesize(_user) }
return size > 0;
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
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 should initially seed the game before start
|
function seedMarket(uint256 eggs) public {
initialized=true;
marketEggs=eggs;
}
| 6,379,304 |
./partial_match/1/0xB48077d89fa302B257f56aA01C7F86dd279B79F3/sources/contracts/GhostERC721Upgradeable/GERC721Upgradeable.sol
|
Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./
|
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = GERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
| 16,182,960 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "library.sol";
contract PausablePool is Context{
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _poolerPaused;
bool private _buyerPaused;
/**
* @dev Modifier to make a function callable only when the pooler is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenPoolerNotPaused() {
require(!_poolerPaused, "paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPoolerPaused() {
require(_poolerPaused, "not paused");
_;
}
/**
* @dev Modifier to make a function callable only when the buyer is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenBuyerNotPaused() {
require(!_buyerPaused, "paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenBuyerPaused() {
require(_buyerPaused, "not paused");
_;
}
/**
* @dev Returns true if the pooler is paused, and false otherwise.
*/
function poolerPaused() public view returns (bool) {
return _poolerPaused;
}
/**
* @dev Returns true if the buyer is paused, and false otherwise.
*/
function buyerPaused() public view returns (bool) {
return _buyerPaused;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The pooler must not be paused.
*/
function _pausePooler() internal whenPoolerNotPaused {
_poolerPaused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The pooler must be paused.
*/
function _unpausePooler() internal whenPoolerPaused {
_poolerPaused = false;
emit Unpaused(_msgSender());
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The buyer must not be paused.
*/
function _pauseBuyer() internal whenBuyerNotPaused {
_buyerPaused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The buyer must be paused.
*/
function _unpauseBuyer() internal whenBuyerPaused {
_buyerPaused = false;
emit Unpaused(_msgSender());
}
}
/**
* @title base contract for option pool
*/
abstract contract PandaBase is IOptionPool, PausablePool{
using SafeERC20 for IERC20;
using SafeERC20 for IOption;
using SafeMath for uint;
using Address for address payable;
// initialization once
bool private inited;
// pool direction enum
enum PoolDirection{ CALL, PUT }
/// @dev pool direction
PoolDirection public immutable _direction;
// option durations
uint16 [] private _durations = [300,900,1800,2700,3600];
/**
* @dev option creation factory, set this based on blockchain,
* constructor will fail if the address is illegal.
*/
// BSC
IPandaFactory internal constant pandaFactory = IPandaFactory(0xddE5b0c676d6A94540F5A2A91C7a5b75eaCBBEe0);
uint256 public collateral; // collaterals in this pool
uint256 internal constant SHARE_MULTIPLIER = 1e18; // share multiplier to avert division underflow
uint256 public constant POOLER_FEE = 5e16; // charge 0.05 BNB for each deposit and withdraw
mapping (address => uint256) internal _premiumBalance; // tracking pooler's claimable premium
mapping (address => uint256) internal _opaBalance; // tracking pooler's claimable OPA tokens
mapping (address => uint256) internal _profitsBalance; // tracking buyer's claimable profits
IOption [] internal _options; // all option contracts
address internal _owner; // owner of this contract
IERC20 public USDTContract; // USDT asset contract address
AggregatorV3Interface public priceFeed; // chainlink price feed
uint8 assetDecimal; // asset decimal
CDFDataInterface public cdfDataContract; // cdf data contract;
uint8 public utilizationRate = 50; // utilization rate of the pool in percent
uint8 public maxUtilizationRate = 75; // max utilization rate of the pool in percent
uint16 public sigma = 70; // current sigma
uint256 private _refreshPeriod = 3600; // sigma refresh period
uint256 private _sigmaSoldOptions; // sum total options sold in a period
uint256 private _sigmaTotalOptions; // sum total options issued
uint256 private _nextRefresh = block.timestamp + _refreshPeriod; // expected next refreshing time;
// tracking pooler's collateral with
// the token contract of the pooler;
IPoolerToken public poolerTokenContract;
address public poolManager; // platform contract
address payable public updaterAddress = 0x3639e068C9c4BB24292a9F3cB9698E03bD6Ee01A; // updater address
IERC20 public OPAToken = IERC20(0xA2F89a3be1bAda5Eb9D58D23EDc2E2FE0F82F4b0) ; // OPA token contract
address public rewardAccount = 0x38A09Ec80aA2c5fc6E92a65E98a4e43e4dAb53b4; // OPA reward account
/**
* OPA Rewarding
*/
/// @dev block reward for this pool
uint256 public OPABlockReward = 0;
/// @dev round index mapping to accumulate share.
mapping (uint => uint) private _opaAccShares;
/// @dev mark pooler's highest settled OPA round.
mapping (address => uint) private _settledOPARounds;
/// @dev a monotonic increasing OPA round index, STARTS FROM 1
uint256 private _currentOPARound = 1;
// @dev last OPA reward block
uint256 private _lastRewardBlock = block.number;
event OPARewardSet(address account, uint256 blockReward);
/**
* OPA Vesting
*/
IVesting public VestingContract = IVesting(0xe135C31Fc21A4962eA5000AC295885bcfd635293);
/**
* @dev settlement economy
* we push some entropy to this array for each user operation
* and pop some of the array when update to refund to caller.
*/
uint256[] private entropy;
/**
* @dev Modifier to make a function callable only by owner
*/
modifier onlyOwner() {
require(msg.sender == _owner, "restricted");
_;
}
/**
* @dev Modifier to make a function callable only by poolerTokenContract
*/
modifier onlyPoolerTokenContract() {
require(msg.sender == address(poolerTokenContract), "restricted");
_;
}
/**
* @dev Modifier to make a function callable only by pool manager
*/
modifier onlyPoolManager() {
require(msg.sender == address(poolManager), "restricted");
_;
}
/**
* @dev Modifier to make a function callable only by options
*/
modifier onlyOptions() {
// privilege check
bool isFromOption;
for (uint i = 0; i < _options.length; i++) {
if (address(_options[i]) == msg.sender) {
isFromOption = true;
break;
}
}
require(isFromOption);
_;
}
/**
* @dev abstract function for current option supply per slot
*/
function _slotSupply(uint assetPrice) internal view virtual returns(uint);
/**
* @dev abstract function to calculate option profits
*/
function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view virtual returns(uint256);
/**
* @dev abstract function to send back option profits
*/
function _sendProfits(address payable account, uint256 amount) internal virtual;
/**
* @dev abstract function to get total pledged collateral
*/
function _totalPledged() internal view virtual returns (uint);
constructor(AggregatorV3Interface priceFeed_, uint8 assetDecimal_, PoolDirection direction_) public {
_owner = msg.sender;
priceFeed = priceFeed_;
assetDecimal = assetDecimal_;
_direction = direction_;
// contract references
USDTContract = IERC20(pandaFactory.getUSDTContract());
cdfDataContract = CDFDataInterface(pandaFactory.getCDF());
// set default poolManager
poolManager = msg.sender;
}
/**
* @dev Option initialization function.
*/
function init() public onlyOwner {
require(!inited, "inited");
inited = true;
// creation of options
for (uint i=0;i<_durations.length;i++) {
_options.push(pandaFactory.createOption(_durations[i], assetDecimal, IOptionPool(this)));
}
// first update;
update();
}
/**
* @dev Returns the owner of this contract
*/
function owner() external override view returns (address) {
return _owner;
}
/**
* @dev transfer ownership
*/
function transferOwnership(address newOwner) external override onlyOwner {
require(newOwner != address(0), "zero");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
*@dev pooler & buyer pausing
*/
function pausePooler() external override onlyOwner { _pausePooler(); }
function unpausePooler() external override onlyOwner { _unpausePooler(); }
function pauseBuyer() external override onlyOwner { _pauseBuyer(); }
function unpauseBuyer() external override onlyOwner { _unpauseBuyer(); }
/**
* @notice check remaining options for the option contract
*/
function optionsLeft(IOption optionContract) external override view returns (uint256 optionsleft, uint round) {
return (optionContract.balanceOf(address(this)), optionContract.getRound());
}
/**
* @notice buy options via USDT, pool receive premium
*/
function buy(uint amount, IOption optionContract, uint round) external override whenBuyerNotPaused {
// make sure optionContract is in this pool
bool optionValid;
for (uint i = 0;i< _options.length;i++) {
if (_options[i] == optionContract) {
optionValid = true;
break;
}
}
require(optionValid,"option invalid");
// check if option current round is the given round, we cannot buy previous rounds
require (optionContract.getRound() == round, "expired");
// cap amount to remaing options
if (optionContract.balanceOf(address(this)) < amount) {
amount = optionContract.balanceOf(address(this));
}
// calculate premium cost
uint premium = premiumCost(amount, optionContract);
// transfer premium USDTs to this pool
USDTContract.safeTransferFrom(msg.sender, address(this), premium);
// transfer options to msg.sender
optionContract.safeTransfer(msg.sender, amount);
// credit premium to option contract
optionContract.addPremium(msg.sender, premium);
// log
emit Buy(msg.sender, address(optionContract), round, amount, premium);
// entropy storage to refund to update() caller
entropy.push(block.number);
// OPTION PARAMETERS MAINTENANCE
// sigma: count sold options
_sigmaSoldOptions = _sigmaSoldOptions.add(amount);
// other periodical refresh
if (block.timestamp > _nextRefresh) {
updateSigma();
}
// open new round, one caller will get refund for an effective update
if (block.timestamp > getNextUpdateTime()) {
update();
}
}
/**
* @dev set OPA reward per height
*/
function setOPAReward(uint256 reward) external onlyOwner {
// settle previous rewards
updateOPAReward();
// set new block reward
OPABlockReward = reward;
// log
emit OPARewardSet(msg.sender, reward);
}
/**
* @dev convert sigma to index, sigma will be rounded to nearest index
*/
function _sigmaToIndex() private view returns(uint) {
// sigma to index
require(sigma >=15 && sigma <=145, "[15,145]");
uint sigmaIndex = sigma / 5;
return sigmaIndex;
}
/**
* @notice check option cost for given amount of option
*/
function premiumCost(uint amount, IOption optionContract) public override view returns(uint) {
// expiry check
if (block.timestamp >= optionContract.expiryDate()) {
return 0;
}
// rounding to nearest duration
uint timediff = optionContract.expiryDate().sub(block.timestamp).add(60);
uint duration = timediff.div(120).mul(120); // round to 2min
// align duration to [120, 3600]
if (duration < 120) {
duration = 120;
} else if (duration > 3600) {
duration = 3600;
}
// notice the CDF is already multiplied by cdfDataContract.Amplifier()
uint cdf = cdfDataContract.CDF(duration, _sigmaToIndex());
// calculate premium for option
uint currentPrice = getAssetPrice();
uint strikePrice = optionContract.strikePrice();
// calculate USDT profits based on current price
uint realtimeProfits;
if (_direction == PoolDirection.CALL) {
// @dev convert asset profits to USDT at current price
realtimeProfits = _calcProfits(currentPrice, strikePrice, amount)
.mul(currentPrice)
.div(10 ** uint(optionContract.decimals()));
} else {
realtimeProfits = _calcProfits(currentPrice, strikePrice, amount);
}
// price in the realtime profits to avoid arbitrage.
// @dev note the price is for 10 ** option decimals
return realtimeProfits + amount * currentPrice * cdf / (10 ** uint(optionContract.decimals())) / cdfDataContract.Amplifier();
}
/**
* @notice list all options
*/
function listOptions() external override view returns (IOption []memory) {
return _options;
}
/**
* @notice get current utilization rate
*/
function currentUtilizationRate() external override view returns (uint256) {
if (collateral > 0) {
return _totalPledged().mul(100).div(collateral);
}
return 0;
}
/**
* @notice get next update time
*/
function getNextUpdateTime() public override view returns (uint) {
uint nextUpdateTime = block.timestamp.add(1 days);
for (uint i = 0;i< _options.length;i++) {
if (_options[i].expiryDate() < nextUpdateTime) {
nextUpdateTime = _options[i].expiryDate();
}
}
return nextUpdateTime;
}
/**
* @notice set refresh period
*/
function setRefreshPeriod(uint period) external override {
require(period > 0, "postive");
_refreshPeriod = period;
}
/**
* @notice update of options, triggered by anyone periodically
*/
function update() public override {
uint256 startGas = gasleft();
// load chainlink price
uint assetPrice = getAssetPrice();
// create a memory copy of array
IOption [] memory options = _options;
// accumulated manager's USDT revenue
uint256 accManagerRevenue;
uint256 accManagerAssetRevenue;
// settle all options
for (uint i = 0;i< options.length;i++) {
if (block.timestamp >= options[i].expiryDate()) { // expired
(uint256 premium, uint256 asset) = _settleOption(options[i], assetPrice);
accManagerRevenue += premium;
accManagerAssetRevenue += asset;
} else { // mark unexpired by clearning 0
options[i] = IOption(0);
}
}
// calculate supply for a slot after settlement,
// notice we must settle options before option reset, otherwise
// we cannot get a correct slot supply due to COLLATERAL WRITE DOWN
// when multiple options settles at once.
uint slotSupply = _slotSupply(assetPrice);
for (uint i = 0;i < options.length;i++) {
if (options[i] != IOption(0)) { // we only check expiryDate once, it's expensive.
// reset option with new slot supply
options[i].resetOption(assetPrice, slotSupply);
// sigma: count newly issued options
_sigmaTotalOptions = _sigmaTotalOptions.add(slotSupply);
}
}
// transfer manager's USDT premium
if (accManagerRevenue > 0) {
USDTContract.safeTransfer(poolManager, accManagerRevenue);
}
// transfer manager's asset revenue
if (accManagerAssetRevenue > 0) {
_sendProfits(payable(poolManager), accManagerAssetRevenue);
}
// compute gas used until now;
// gas usage +STORAGEMOD -STORAGEKILL = -10000
uint needKills = (startGas - gasleft()) / 10000;
// maximum 50% refund;
needKills = needKills/2 + 1;
// entropy limit
if (needKills > entropy.length) {
needKills = entropy.length;
}
// refund gas via STORAGEKILL for any caller
for (uint i = 0;i<needKills;i++) {
entropy.pop();
}
}
/**
* @dev settle option contract
*
* ASSUMPTION:
* if one pooler's token amount keeps unchanged after settlement, then
* accmulated premiumShare * (pooler token)
* is the share for one pooler.
*/
function _settleOption(IOption option, uint settlePrice) internal returns (uint256 managerRevenue, uint256 managerAssetRevenue) {
uint totalSupply = option.totalSupply();
uint strikePrice = option.strikePrice();
// count total sold options
uint totalOptionSold = totalSupply.sub(option.balanceOf(address(this)));
// calculate user's total profits, ALREADY MULTIPLIED WITH 99%
uint totalProfits = _calcProfits(settlePrice, strikePrice, totalOptionSold);
// substract collateral
// buyer's profits is pooler's loss
if (totalProfits > 0) {
// 1% profits belongs to manager
managerAssetRevenue = totalProfits.div(99);
collateral = collateral.sub(totalProfits).sub(managerAssetRevenue);
}
// settle preimum dividends
uint poolerTotalSupply = poolerTokenContract.totalSupply();
uint totalPremiums = option.totalPremiums();
uint round = option.getRound();
// settle premium share
uint roundPremiumShare;
if (poolerTotalSupply > 0) {
// 1% belongs to platform
managerRevenue = totalPremiums.div(100);
// 99% belongs to all pooler
roundPremiumShare = totalPremiums.sub(managerRevenue)
.mul(SHARE_MULTIPLIER) // mul share with SHARE_MULTIPLIER to avert from underflow
.div(poolerTotalSupply);
}
// set the accumulated premiumShare if round > 0
if (round > 0) {
roundPremiumShare = roundPremiumShare.add(option.getRoundAccPremiumShare(round-1));
}
option.setRoundAccPremiumShare(round, roundPremiumShare);
}
/**
* @dev update accumulated OPA block reward until block
*/
function updateOPAReward() internal {
// skip round changing in the same block
if (_lastRewardBlock == block.number) {
return;
}
uint poolerTotalSupply = poolerTokenContract.totalSupply();
// postpone OPA rewarding if there is none pooler
if (poolerTotalSupply == 0) {
return;
}
// settle OPA share for [_lastRewardBlock, block.number]
uint blocksToReward = block.number.sub(_lastRewardBlock);
uint mintedOPA = OPABlockReward.mul(blocksToReward);
uint roundOPAShare = mintedOPA.mul(SHARE_MULTIPLIER)
.div(poolerTotalSupply);
// mark block rewarded;
_lastRewardBlock = block.number;
// accumulate OPA share
_opaAccShares[_currentOPARound] = roundOPAShare.add(_opaAccShares[_currentOPARound-1]);
// next round setting
_currentOPARound++;
}
/**
* @dev function to update sigma value periodically
*/
function updateSigma() internal {
// sigma: metrics updates hourly
if (_sigmaTotalOptions > 0) {
uint16 s = sigma;
// update sigma
uint rate = _sigmaSoldOptions.mul(100).div(_sigmaTotalOptions);
// sigma range [15, 145]
if (rate > 90 && s < 145) {
s += 5;
} else if (rate < 50 && s > 15) {
s -= 5;
}
sigma = s;
}
// new metrics
uint sigmaTotalOptions;
uint sigmaSoldOptions;
// create a memory copy of array
IOption [] memory options = _options;
// rebuild sold/total metrics
for (uint i = 0;i< options.length;i++) {
// sum all issued options and sold options
uint supply = options[i].totalSupply();
uint sold = supply.sub(options[i].balanceOf(address(this)));
sigmaTotalOptions = sigmaTotalOptions.add(supply);
sigmaSoldOptions = sigmaSoldOptions.add(sold);
}
// set back to contract storage
_sigmaTotalOptions = sigmaTotalOptions;
_sigmaSoldOptions = sigmaSoldOptions;
// set next refresh time to at least one hour later
_nextRefresh += _refreshPeriod;
}
/**
* @notice adjust sigma manually
*/
function adjustSigma(uint16 newSigma) external override onlyOwner {
require (newSigma % 5 == 0, "needs 5*N");
require (newSigma >= 15 && newSigma <= 145, "[15,145]");
sigma = newSigma;
}
/**
* @notice poolers sum premium USDTs;
*/
function checkPremium(address account) external override view returns(uint256 premium) {
uint accountCollateral = poolerTokenContract.balanceOf(account);
premium = _premiumBalance[account];
for (uint i = 0; i < _options.length; i++) {
IOption option = _options[i];
uint currentRound = option.getRound();
uint lastSettledRound = option.getSettledRound(account);
uint roundPremium = option.getRoundAccPremiumShare(currentRound-1).sub(option.getRoundAccPremiumShare(lastSettledRound))
.mul(accountCollateral)
.div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER
premium = premium.add(roundPremium);
}
return (premium);
}
/**
* @notice poolers claim premium USDTs;
*/
function claimPremium() external override whenPoolerNotPaused {
// settle un-distributed premiums in rounds to _premiumBalance;
_settlePooler(msg.sender);
// premium balance modification
uint amountUSDTPremium = _premiumBalance[msg.sender];
delete _premiumBalance[msg.sender]; // zero premium balance
// transfer premium
USDTContract.safeTransfer(msg.sender, amountUSDTPremium);
// log
emit PremiumClaim(msg.sender, amountUSDTPremium);
}
/**
* @notice poolers sum unclaimed OPA;
*/
function checkOPA(address account) external override view returns(uint256 opa) {
uint poolerTotalSupply = poolerTokenContract.totalSupply();
uint accountCollateral = poolerTokenContract.balanceOf(account);
uint lastSettledOPARound = _settledOPARounds[account];
// poolers OPA reward = settledOPA + unsettledOPA + newMinedOPA
uint unsettledOPA = _opaAccShares[_currentOPARound-1].sub(_opaAccShares[lastSettledOPARound]);
uint newMinedOPAShare;
if (poolerTotalSupply > 0) {
uint blocksToReward = block.number.sub(_lastRewardBlock);
uint mintedOPA = OPABlockReward.mul(blocksToReward);
// OPA share per pooler token
newMinedOPAShare = mintedOPA.mul(SHARE_MULTIPLIER)
.div(poolerTotalSupply);
}
return _opaBalance[account] + (unsettledOPA + newMinedOPAShare).mul(accountCollateral)
.div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER;
}
/**
* @notice claim OPA;
*/
function claimOPA() external override whenPoolerNotPaused {
// settle un-distributed OPA in rounds to _opaBalance;
_settlePooler(msg.sender);
// OPA balance modification
uint amountOPA = _opaBalance[msg.sender];
delete _opaBalance[msg.sender]; // zero OPA balance
// transfer OPA to vesting contract
OPAToken.safeTransferFrom(rewardAccount, address(VestingContract), amountOPA);
// vest the amount for the sender
VestingContract.vest(msg.sender, amountOPA);
// log
emit OPAClaimed(msg.sender, amountOPA);
}
/**
* @notice settle premium in rounds while pooler token transfers.
*/
function settlePooler(address account) external override onlyPoolerTokenContract {
_settlePooler(account);
}
/**
* @notice settle premium in rounds to _premiumBalance,
* settle premium happens before any pooler token exchange such as ERC20-transfer,mint,burn,
* and manually claimPremium;
*
*/
function _settlePooler(address account) internal {
uint accountCollateral = poolerTokenContract.balanceOf(account);
// premium settlement
uint premiumBalance = _premiumBalance[account];
for (uint i = 0; i < _options.length; i++) {
IOption option = _options[i];
uint lastSettledRound = option.getSettledRound(account);
uint newSettledRound = option.getRound() - 1;
// premium
uint roundPremium = option.getRoundAccPremiumShare(newSettledRound).sub(option.getRoundAccPremiumShare(lastSettledRound))
.mul(accountCollateral)
.div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER
premiumBalance = premiumBalance.add(roundPremium);
// mark new settled round
option.setSettledRound(newSettledRound, account);
}
// log settled premium
emit PremiumSettled(msg.sender, accountCollateral, premiumBalance.sub(_premiumBalance[account]));
// set back balance to storage
_premiumBalance[account] = premiumBalance;
// OPA settlement for each pooler token balance change
{
// update OPA reward snapshot
updateOPAReward();
// settle this account
uint lastSettledOPARound = _settledOPARounds[account];
uint newSettledOPARound = _currentOPARound - 1;
// round OPA
uint roundOPA = _opaAccShares[newSettledOPARound].sub(_opaAccShares[lastSettledOPARound])
.mul(accountCollateral)
.div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER
// update OPA balance
_opaBalance[account] += roundOPA;
// mark new settled OPA round
_settledOPARounds[account] = newSettledOPARound;
}
}
/**
* @notice net-withdraw amount;
*/
function NWA() public view override returns (uint) {
// get minimum collateral
uint minCollateral = _totalPledged() * 100 / maxUtilizationRate;
if (minCollateral > collateral) {
return 0;
}
// net withdrawable amount
return collateral.sub(minCollateral);
}
/**
* @notice check claimable buyer's profits
*/
function checkProfits(address account) external override view returns (uint256 profits) {
// load from profits balance
profits = _profitsBalance[account];
// sum all profits from all options
for (uint i = 0; i < _options.length; i++) {
profits += checkOptionProfits(_options[i], account);
}
return profits;
}
/**
* @notice check profits in an option
*/
function checkOptionProfits(IOption option, address account) internal view returns (uint256 amount) {
uint unclaimedRound = option.getUnclaimedProfitsRound(account);
if (unclaimedRound == option.getRound()) {
return 0;
}
// accumulate profits in _profitsBalance
uint settlePrice = option.getRoundSettlePrice(unclaimedRound);
uint strikePrice = option.getRoundStrikePrice(unclaimedRound);
uint optionAmount = option.getRoundBalanceOf(unclaimedRound, account);
return _calcProfits(settlePrice, strikePrice, optionAmount);
}
/**
* @notice buyers claim option profits
*/
function claimProfits() external override whenBuyerNotPaused {
// settle profits in options
for (uint i = 0; i < _options.length; i++) {
_settleBuyer(_options[i], msg.sender);
}
// load and clean profits
uint256 accountProfits = _profitsBalance[msg.sender];
delete _profitsBalance[msg.sender];
// send profits
_sendProfits(msg.sender, accountProfits);
// log
emit ProfitsClaim(msg.sender, accountProfits);
}
/**
* @notice settle profits while option token transfers.
*/
function settleBuyer(address account) external override onlyOptions {
_settleBuyer(IOption(msg.sender), account);
}
/**
* @notice settle profits in rounds to _profitsBalance,
* settle buyer happens before any option token exchange such as ERC20-transfer,mint,burn,
* and manually claimProfits;
*
*/
function _settleBuyer(IOption option, address account) internal {
uint unclaimedRound = option.getUnclaimedProfitsRound(account);
uint currentRound = option.getRound();
// current round is always unsettled
if (unclaimedRound == currentRound) {
return;
}
// accumulate profits in _profitsBalance
uint settlePrice = option.getRoundSettlePrice(unclaimedRound);
uint strikePrice = option.getRoundStrikePrice(unclaimedRound);
uint256 optionAmount = option.getRoundBalanceOf(unclaimedRound, account);
uint256 profits = _calcProfits(settlePrice, strikePrice, optionAmount);
// add profits to balance;
_profitsBalance[account] += profits;
// set current round unclaimed
option.setUnclaimedProfitsRound(currentRound, account);
// log settled profits
emit ProfitsSettled(msg.sender, address(option), unclaimedRound, profits);
}
/**
* @notice set pool manager
*/
function setPoolManager(address poolManager_) external onlyOwner {
poolManager = poolManager_;
}
/**
* @notice set updater address
*/
function setUpdater(address payable updater_) external onlyOwner {
updaterAddress = updater_;
}
/**
* @notice set OPA token
*/
function setOPAToken(IERC20 OPAToken_) external onlyOwner {
OPAToken = OPAToken_;
}
/**
* @notice set OPA transfer account
*/
function setOPARewardAccount(address rewardAccount_) external onlyOwner {
rewardAccount = rewardAccount_;
}
/**
* @notice set Vesting contract
*/
function setVestingContract(IVesting vestingContract_) external onlyOwner {
VestingContract = vestingContract_;
}
/**
* @notice set utilization rate by owner
*/
function setUtilizationRate(uint8 rate) external override onlyOwner {
require(rate >=0 && rate <= 100, "[0,100]");
utilizationRate = rate;
}
/**
* @notice set max utilization rate by owner
*/
function setMaxUtilizationRate(uint8 maxrate) external override onlyOwner {
require(maxrate >=0 && maxrate <= 100, "[0,100]");
require(maxrate > utilizationRate, "less than rate");
maxUtilizationRate = maxrate;
}
/**
* @dev get the price for asset with regarding to asset decimals
* Example:
* for ETH price oracle, this function returns the USDT price for 1 ETH
*/
function getAssetPrice() public view returns(uint) {
(, int latestPrice, , , ) = priceFeed.latestRoundData();
if (latestPrice > 0) { // convert to USDT decimal
return uint(latestPrice).mul(10 ** uint256(USDTContract.decimals()))
.div(10 ** uint256(priceFeed.decimals()));
}
return 0;
}
}
/**
* @title Implementation of Native Call Option Pool
* NativeCallOptionPool Call Option Pool use native currency as collateral and bets
* on Chainlink Oracle Price Feed.
*/
contract NativeCallOptionPool is PandaBase {
string private _name;
/**
* @param priceFeed Chainlink contract for asset price
*/
constructor(string memory name_, AggregatorV3Interface priceFeed)
PandaBase(priceFeed, 18, PoolDirection.CALL)
public {
_name = name_;
// creation of pooler token
poolerTokenContract = pandaFactory.createPoolerToken(18, IOptionPool(this));
}
/**
* @dev Returns the pool of the contract.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @notice deposit ethers to this pool directly.
*/
function deposit() external whenPoolerNotPaused payable {
require(msg.value > POOLER_FEE, "0 value");
uint256 value = msg.value.sub(POOLER_FEE);
poolerTokenContract.mint(msg.sender, value);
collateral = collateral.add(value);
// log
emit Deposit(msg.sender, value);
// transfer POOLER_FEE to updaterAddress
updaterAddress.sendValue(POOLER_FEE);
}
/**
* @notice withdraw the pooled ethers;
*/
function withdraw(uint amount) external whenPoolerNotPaused payable {
require (amount <= poolerTokenContract.balanceOf(msg.sender), "balance exceeded");
require (amount <= NWA(), "collateral exceeded");
require(msg.value >= POOLER_FEE, "0 fee");
// burn pooler token
poolerTokenContract.burn(msg.sender, amount);
// substract collateral
collateral = collateral.sub(amount);
// transfer ETH to msg.sender
msg.sender.sendValue(amount);
// log
emit Withdraw(msg.sender, amount);
// transfer POOLER_FEE to updaterAddress
updaterAddress.sendValue(msg.value);
}
/**
* @notice sum total collaterals pledged
*/
function _totalPledged() internal view override returns (uint amount) {
for (uint i = 0;i< _options.length;i++) {
amount += _options[i].totalSupply();
}
}
/**
* @dev function to calculate option profits
*/
function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view override returns(uint256 profits) {
// call options get profits due to price rising.
if (settlePrice > strikePrice && strikePrice > 0) {
// calculate ratio
uint ratio = settlePrice.sub(strikePrice)
.mul(1e12) // mul by 1e12 here to avoid underflow
.div(strikePrice);
// calculate ETH profits of this amount
uint holderETHProfit = ratio.mul(optionAmount)
.div(1e12); // remember to div by 1e12 previous mul-ed
return holderETHProfit.mul(99).div(100);
}
}
/**
* @dev send profits back to sender's address
*/
function _sendProfits(address payable account, uint256 amount) internal override {
account.sendValue(amount);
}
/**
* @dev get current new option supply
*/
function _slotSupply(uint) internal view override returns(uint) {
return collateral.mul(utilizationRate)
.div(100)
.div(_options.length);
}
}
/**
* @title Implementation of ERC20 Asset Call Option Pool
* ERC20 Asset Call Option Pool use ERC20 asset as collateral and bets
* on Chainlink Oracle Price Feed.
*/
contract ERC20CallOptionPool is PandaBase {
string private _name;
IERC20 public assetContract;
/**
* @param priceFeed Chainlink contract for asset price
* @param assetContract_ ERC20 asset contract address
*/
constructor(string memory name_, IERC20 assetContract_, AggregatorV3Interface priceFeed)
PandaBase(priceFeed, assetContract_.decimals(), PoolDirection.CALL)
public {
_name = name_;
assetContract = assetContract_;
poolerTokenContract = pandaFactory.createPoolerToken(assetContract.decimals(), IOptionPool(this));
}
/**
* @dev Returns the pool of the contract.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @notice deposit asset to this pool directly.
*/
function depositAsset(uint256 amountAsset) external whenPoolerNotPaused payable {
require(amountAsset > 0, "0 value");
require(msg.value >= POOLER_FEE, "0 fee");
// transfer POOLER_FEE to updaterAddress
updaterAddress.sendValue(msg.value);
assetContract.safeTransferFrom(msg.sender, address(this), amountAsset);
poolerTokenContract.mint(msg.sender, amountAsset);
collateral = collateral.add(amountAsset);
// log
emit Deposit(msg.sender, amountAsset);
}
/**
* @notice withdraw the pooled ethers;
*/
function withdrawAsset(uint amountAsset) external whenPoolerNotPaused payable {
require (amountAsset <= poolerTokenContract.balanceOf(msg.sender), "balance exceeded");
require (amountAsset <= NWA(), "collateral exceeded");
require(msg.value >= POOLER_FEE, "0 fee");
// transfer POOLER_FEE to updaterAddress
updaterAddress.sendValue(msg.value);
// burn pooler token
poolerTokenContract.burn(msg.sender, amountAsset);
// substract collateral
collateral = collateral.sub(amountAsset);
// transfer asset back to msg.sender
assetContract.safeTransfer(msg.sender, amountAsset);
// log
emit Withdraw(msg.sender, amountAsset);
}
/**
* @notice sum total collaterals pledged
*/
function _totalPledged() internal view override returns (uint amount) {
for (uint i = 0;i< _options.length;i++) {
amount += _options[i].totalSupply();
}
}
/**
* @dev send profits back to account
*/
function _sendProfits(address payable account, uint256 amount) internal override {
assetContract.safeTransfer(account, amount);
}
/**
* @dev function to calculate option profits
*/
function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view override returns(uint256 profits) {
// call options get profits due to price rising.
if (settlePrice > strikePrice && strikePrice > 0) {
// calculate ratio
uint ratio = settlePrice.sub(strikePrice)
.mul(1e12) // mul by 1e12 here to avoid from underflow
.div(strikePrice);
// calculate asset profits of this amount
uint holderAssetProfit = ratio.mul(optionAmount)
.div(1e12); // remember to div by 1e12 previous mul-ed
return holderAssetProfit.mul(99).div(100);
}
}
/**
* @notice get current new option supply
*/
function _slotSupply(uint) internal view override returns(uint) {
return collateral.mul(utilizationRate)
.div(100)
.div(_options.length);
}
}
/**
* @title Implementation of Put Option Pool
* Put Option Pool requires USDT as collateral and
* bets on Chainlink Oracle Price Feed of one asset.
*/
contract PutOptionPool is PandaBase {
string private _name;
uint private immutable assetPriceUnit;
/**
* @param priceFeed Chainlink contract for asset price
* @param assetDecimal the decimal of the price
*/
constructor(string memory name_, uint8 assetDecimal, AggregatorV3Interface priceFeed)
PandaBase(priceFeed, assetDecimal, PoolDirection.PUT)
public {
_name = name_;
assetPriceUnit = 10 ** uint(assetDecimal);
poolerTokenContract = pandaFactory.createPoolerToken(USDTContract.decimals(), IOptionPool(this));
}
/**
* @dev Returns the pool of the contract.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @notice deposit of Tether USDTS, user needs
* to approve() to this contract address first,
* and call with the given amount.
*/
function depositUSDT(uint256 amountUSDT) external whenPoolerNotPaused payable {
require(amountUSDT > 0, "0 value");
require(msg.value >= POOLER_FEE, "0 fee");
// transfer POOLER_FEE to updaterAddress
updaterAddress.sendValue(msg.value);
USDTContract.safeTransferFrom(msg.sender, address(this), amountUSDT);
poolerTokenContract.mint(msg.sender, amountUSDT);
collateral = collateral.add(amountUSDT);
// log
emit Deposit(msg.sender, amountUSDT);
}
/**
* @notice withdraw the pooled USDT;
*/
function withdrawUSDT(uint amountUSDT) external whenPoolerNotPaused payable {
require (amountUSDT <= poolerTokenContract.balanceOf(msg.sender), "balance exceeded");
require (amountUSDT <= NWA(), "collateral exceeded");
require (msg.value >= POOLER_FEE, "0 fee");
// transfer POOLER_FEE to updaterAddress
updaterAddress.sendValue(msg.value);
// burn pooler token
poolerTokenContract.burn(msg.sender, amountUSDT);
// substract collateral
collateral = collateral.sub(amountUSDT);
// transfer USDT to msg.sender
USDTContract.safeTransfer(msg.sender, amountUSDT);
// log
emit Withdraw(msg.sender, amountUSDT);
}
/**
* @notice sum total collaterals pledged
*/
function _totalPledged() internal view override returns (uint) {
// sum total collateral in USDT
uint total;
for (uint i = 0;i< _options.length;i++) {
// derive collaterals at issue time
total = total.add(_options[i].totalSupply() * _options[i].strikePrice());
}
// @dev remember to div with asset price unit
total /= assetPriceUnit;
return total;
}
/**
* @dev send profits back to account
*/
function _sendProfits(address payable account, uint256 amount) internal override {
USDTContract.safeTransfer(account, amount);
}
/**
* @dev function to calculate option profits
*/
function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view override returns(uint256 profits) {
if (settlePrice < strikePrice && strikePrice > 0) { // put option get profits at this round
// calculate ratio
uint ratio = strikePrice.sub(settlePrice)
.mul(1e12) // mul 1e12 to avoid from underflow
.div(strikePrice);
// holder share
uint holderShare = ratio.mul(optionAmount);
// convert to USDT profits
uint holderUSDTProfit = holderShare.mul(strikePrice)
.div(1e12) // remember to div 1e12 previous multipied
.div(assetPriceUnit); // remember to div price unit
return holderUSDTProfit.mul(99).div(100);
}
}
/**
* @notice get current new option supply
*/
function _slotSupply(uint assetPrice) internal view override returns(uint) {
// Formula : (collateral / numOptions) * utilizationRate / 100 / (assetPrice/ price unit)
return collateral.mul(utilizationRate)
.mul(assetPriceUnit)
.div(100)
.div(_options.length)
.div(assetPrice);
}
}
|
poolers claim premium USDTs;/ settle un-distributed premiums in rounds to _premiumBalance; premium balance modification transfer premium log
|
function claimPremium() external override whenPoolerNotPaused {
_settlePooler(msg.sender);
uint amountUSDTPremium = _premiumBalance[msg.sender];
USDTContract.safeTransfer(msg.sender, amountUSDTPremium);
emit PremiumClaim(msg.sender, amountUSDTPremium);
}
| 12,715,328 |
./partial_match/1/0xEC45E951BbC61dd83F7ced3e6a18fe4E22de5882/sources/OwnbitMultiSig.sol
|
0x9 is used for spendAnybe careful with any action, data is not included into signature computation. So any data can be included in spendAny.This is usually for some emergent recovery, for example, recovery of NTFs, etc.Owners should not generate 0x9 based signatures in normal cases.transfer tokens from this contract to the destination address
|
function spendAny(address destination, uint256 value, uint8[] vs, bytes32[] rs, bytes32[] ss, bytes data) external {
require(destination != address(this), "Not allow sending to yourself");
require(_validSignature(address(0x9), destination, value, vs, rs, ss), "invalid signatures");
spendNonce = spendNonce + 1;
if (destination.call.value(value)(data)) {
emit SpentAny(destination, value);
}
}
| 3,617,014 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./SuperbToken.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Contract details
* @author Raphael
* @notice This contract is deployed with an ERC20 contract in order to set up a sale,
* the sale last 2 weeks since the owner call the function startSalePeriod(). The ICO is unique,
* the owner cannot set up a new ICO without re deploy the contract.
*
* Tokens and Ether are blocked in the contract during these 2 weeks.
* */
contract InitialCoinOffering is Ownable {
using Address for address payable;
SuperbToken private _token;
uint256 private _supplyInSale;
uint256 private _supplySold;
uint256 private _rate;
mapping(address => uint256) private _tokenBalances;
uint256 private _startTimeEpoch;
/**
* @param owner address of the owner
* @param icoContract address of the ERC20 token contract
* @param supplyInSale amount of token to put in sale
* @param rate amount of token for one ether
* */
event SaleStarted(address indexed owner, address indexed icoContract, uint256 supplyInSale, uint256 rate);
/**
* @param buyer address who bought tokens
* @param amount amount of token bought
* @param totalSupplyBought total amount bought so far
* */
event TokenBought(address indexed buyer, uint256 amount, uint256 totalSupplyBought);
/**
* @param buyer address who claims tokens
* @param amount amount of tokens claimed
* */
event TokenClaimed(address indexed buyer, uint256 amount);
/**
* @dev The constructor set the ERC20 contract address and the owner (Ownable.sol) of the ICO
* @param superbTokenAddress is the deployed contract address of the ERC20 token
* @param owner_ is the owner of the ICO contract, set via the Ownable contract
* */
constructor(address superbTokenAddress, address owner_) Ownable() {
_token = SuperbToken(superbTokenAddress);
transferOwnership(owner_);
}
/**
* @notice This modifier is used in the _buyToken() function to prevent a purchase if it is out of the sale period.
* */
modifier isSalePeriod() {
require(_startTimeEpoch != 0, "InitialCoinOffering: the sale is not started yet.");
if (_startTimeEpoch != 0) {
require(block.timestamp < _startTimeEpoch + 2 weeks, "InitialCoinOffering: The sale is over.");
}
_;
}
/**
* @notice buyers can throw directly on the contract address to buy tokens.
* @dev this function call the private _buyToken() function
* */
receive() external payable {
_buyToken(msg.sender, msg.value);
}
/**
* @notice This payable function is used to buy token via the ICO contract.
* As the receive function, it calls the private function _buyToken().
* */
function buyToken() public payable {
_buyToken(msg.sender, msg.value);
}
/**
* @notice This function is called to initiate the sale, this function is callable
* only by the owner and only if:
* - the owner sell less or equal than the total supply
* - the owner have already allowed the smart contract for spend funds
* - the sale is not already started for the first time
*
* The owner have to deploy another contract if he wants to achieve a second ICO.
*
* @param supplyInSale_ is the amount of the supply the owner wants to sell through the ICO
* @param rate_ the number correspond the number of token for 1 ether
* [1 => 1 token = 1 ether]
* [1 000 => 1000 token = 1 ether]
* [1 000 => 1 token = 1 finney]
* [456 => 456 token = 1 ether]
* */
function startSalePeriod(uint256 supplyInSale_, uint256 rate_) public onlyOwner {
require(
supplyInSale_ <= _token.totalSupply(),
"InitialCoinOffering: you cannot sell more than the total supply."
);
require(
supplyInSale_ <= _token.allowance(owner(), address(this)),
"InitialCoinOffering: you have not allowed the funds yet."
);
require(_startTimeEpoch == 0, "InitialCoinOffering: the sale is already launched.");
_startTimeEpoch = block.timestamp;
_supplyInSale = supplyInSale_;
_rate = rate_;
emit SaleStarted(owner(), address(this), supplyInSale_, rate_);
}
/**
* @notice This function is called to get tokens once the ICO is over.
*
* @dev in this function the ICO contract send tokens directly to the buyer,
* since tokens where moved to the contract in the buyToken() function.
* */
function claimToken() public {
require(
block.timestamp > _startTimeEpoch + 2 weeks,
"InitialCoinOffering: you cannot claim tokens before the sale ends."
);
require(_tokenBalances[msg.sender] != 0, "InitialCoinOffering: You have nothing to claim.");
uint256 amount = _tokenBalances[msg.sender];
_tokenBalances[msg.sender] = 0;
_token.transfer(msg.sender, amount);
emit TokenClaimed(msg.sender, amount);
}
/**
* @notice This function is set for the owner in order to withdraw ether generated by the sale,
* the owner cannot withdraw ethers before the sale end (may be removed).
*
* May it needs a Reentrancy Guard ?
* */
function withdrawSaleProfit() public onlyOwner {
require(address(this).balance != 0, "InitialCoinOffering: there is no ether to withdraw in the contract.");
require(
block.timestamp > _startTimeEpoch + 2 weeks,
"InitialCoinOffering: you cannot withdraw ether before the sale ends."
);
payable(msg.sender).sendValue(address(this).balance);
}
/**
* @return The address of the ERC20 contract
* */
function tokenContract() public view returns (address) {
return address(_token);
}
/**
* @return the number of token for 1 ether
* */
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return The total amount of token minted at the deployment
* */
function supplyInSale() public view returns (uint256) {
return _supplyInSale;
}
/**
* @return The amount of token selled so far
* */
function supplySold() public view returns (uint256) {
return _supplySold;
}
/**
* @param account address checked for token balance
* @return the amount of tokens locked in the contract for the specified address
* */
function tokenBalanceOf(address account) public view returns (uint256) {
return _tokenBalances[account];
}
/**
* @return the amount of ethers locked in the contract
* */
function contractBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* @return the time before the sale end: 0 means the sale have not started yet or the sale is over
* */
function timeBeforeSaleEnd() public view returns (uint256) {
if (_startTimeEpoch == 0) {
return 0;
} else {
return (_startTimeEpoch + 2 weeks) - block.timestamp;
}
}
/**
* @notice This private function is used in the receive() and the buyToken().
*
* If the token supply is lower than the amount of the value set by the buyers,
* this latter is refund and take the remaining supply.
*
* When this function is called, several state variable is updated :
* - the supply in sale decrease
* - the suplly solded increase
* - the token balance of the buyers increase
*
* @dev The amount of solded token is transferred from the owner address to the contract address,
* this way the owner cannot transfer fund that is already bought in the ICO.
* */
function _buyToken(address sender, uint256 amount) private isSalePeriod {
require(_supplyInSale != 0, "InitialCoinOffering: there is no more token in sale.");
uint256 tokenAmount = amount * _rate;
uint256 exceedTokenAmount;
if (_supplyInSale < tokenAmount) {
exceedTokenAmount = tokenAmount - _supplyInSale;
}
_supplyInSale -= tokenAmount - exceedTokenAmount;
_tokenBalances[sender] += tokenAmount - exceedTokenAmount;
_supplySold += tokenAmount - exceedTokenAmount;
_token.transferFrom(owner(), address(this), tokenAmount - exceedTokenAmount);
payable(sender).sendValue(exceedTokenAmount / _rate);
emit TokenBought(sender, tokenAmount - exceedTokenAmount, _supplySold);
}
}
|
return The total amount of token minted at the deployment /
|
function supplyInSale() public view returns (uint256) {
return _supplyInSale;
}
| 6,385,800 |
pragma solidity ^0.4.25;
/*******************************************************************************
*
* Copyright (c) 2019 Decentralization Authority MDAO.
* Released under the MIT License.
*
* ZeroFilters - A crowd-sourced database of "malicious / suspicious" endpoints
* as reported by "trusted" users within the community.
*
* List of Currently Supported Filters*
* -----------------------------------
*
* 1. ABUSE
* - animal | animals
* - child | children
* - man | men
* - woman | women
*
* 2. HARASSMENT
* - bullying
*
* 3. REVENGE
* - porn
*
* 4. TERRORISM
* - ISIS
*
* * This is NOT a complete listing of ALL content violations.
* We are continuing to work along with the community in
* sculpting a transparent and comprehensive package of
* acceptable resource usage.
*
* Version 19.3.11
*
* https://d14na.org
* [email protected]
*/
/*******************************************************************************
*
* 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);
}
/*******************************************************************************
*
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/*******************************************************************************
*
* Zer0netDb Interface
*/
contract Zer0netDbInterface {
/* Interface getters. */
function getAddress(bytes32 _key) external view returns (address);
function getBool(bytes32 _key) external view returns (bool);
function getBytes(bytes32 _key) external view returns (bytes);
function getInt(bytes32 _key) external view returns (int);
function getString(bytes32 _key) external view returns (string);
function getUint(bytes32 _key) external view returns (uint);
/* Interface setters. */
function setAddress(bytes32 _key, address _value) external;
function setBool(bytes32 _key, bool _value) external;
function setBytes(bytes32 _key, bytes _value) external;
function setInt(bytes32 _key, int _value) external;
function setString(bytes32 _key, string _value) external;
function setUint(bytes32 _key, uint _value) external;
/* Interface deletes. */
function deleteAddress(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
}
/*******************************************************************************
*
* @notice ZeroFilters
*
* @dev A key-value store.
*/
contract ZeroFilters is Owned {
/* Initialize predecessor contract. */
address private _predecessor;
/* Initialize successor contract. */
address private _successor;
/* Initialize revision number. */
uint private _revision;
/* Initialize Zer0net Db contract. */
Zer0netDbInterface private _zer0netDb;
/* Set namespace. */
string _NAMESPACE = 'zerofilters';
event Filter(
bytes32 indexed dataId,
bytes metadata
);
/***************************************************************************
*
* Constructor
*/
constructor() public {
/* Set predecessor address. */
_predecessor = 0x0;
/* Verify predecessor address. */
if (_predecessor != 0x0) {
/* Retrieve the last revision number (if available). */
uint lastRevision = ZeroFilters(_predecessor).getRevision();
/* Set (current) revision number. */
_revision = lastRevision + 1;
}
/* Initialize Zer0netDb (eternal) storage database contract. */
// NOTE We hard-code the address here, since it should never change.
_zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af);
}
/**
* @dev Only allow access to an authorized Zer0net administrator.
*/
modifier onlyAuthBy0Admin() {
/* Verify write access is only permitted to authorized accounts. */
require(_zer0netDb.getBool(keccak256(
abi.encodePacked(msg.sender, '.has.auth.for.zerofilters'))) == true);
_; // function code is inserted here
}
/**
* THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER
*/
function () public payable {
/* Cancel this transaction. */
revert('Oops! Direct payments are NOT permitted here.');
}
/***************************************************************************
*
* ACTIONS
*
*/
/**
* Calculate Data Id by Hash
*/
function calcIdByHash(
bytes32 _hash
) public view returns (bytes32 dataId) {
/* Calculate the data id. */
dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.hash.', _hash));
}
/**
* Calculate Data Id by Hostname
*/
function calcIdByHostname(
string _hostname
) external view returns (bytes32 dataId) {
/* Calculate the data id. */
dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.hostname.', _hostname));
}
/**
* Calculate Data Id by Owner
*/
function calcIdByOwner(
address _owner
) external view returns (bytes32 dataId) {
/* Calculate the data id. */
dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.owner.', _owner));
}
/**
* Calculate Data Id by Regular Expression
*/
function calcIdByRegex(
string _regex
) external view returns (bytes32 dataId) {
/* Calculate the data id. */
dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.regex.', _regex));
}
/***************************************************************************
*
* GETTERS
*
*/
/**
* Get Info
*/
function getInfo(
bytes32 _dataId
) external view returns (bytes info) {
/* Return info. */
return _getInfo(_dataId);
}
/**
* Get Info by Hash
*/
function getInfoByHash(
bytes32 _hash
) external view returns (bytes info) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.hash.', _hash));
/* Return info. */
return _getInfo(dataId);
}
/**
* Get Info by Hostname
*/
function getInfoByHostname(
string _hostname
) external view returns (bytes info) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.hostname.', _hostname));
/* Return info. */
return _getInfo(dataId);
}
/**
* Get Info by Owner
*/
function getInfoByOwner(
address _owner
) external view returns (bytes info) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.owner.', _owner));
/* Return info. */
return _getInfo(dataId);
}
/**
* Get Info by Regular Expression
*/
function getInfoByRegex(
string _regex
) external view returns (bytes info) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.regex.', _regex));
/* Return info. */
return _getInfo(dataId);
}
/**
* Get Info
*
* Retrieves the JSON-formatted, byte-encoded data stored at
* the location of `_dataId`.
*/
function _getInfo(
bytes32 _dataId
) private view returns (bytes info) {
/* Retrieve info. */
info = _zer0netDb.getBytes(_dataId);
}
/**
* Get Revision (Number)
*/
function getRevision() public view returns (uint) {
return _revision;
}
/**
* Get Predecessor (Address)
*/
function getPredecessor() public view returns (address) {
return _predecessor;
}
/**
* Get Successor (Address)
*/
function getSuccessor() public view returns (address) {
return _successor;
}
/***************************************************************************
*
* SETTERS
*
*/
/**
* Set Info by Hash
*/
function setInfoByHash(
bytes32 _hash,
bytes _data
) onlyAuthBy0Admin external returns (bool success) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.hash.', _hash));
/* Set info. */
return _setInfo(dataId, _data);
}
/**
* Set Info by Hostname
*/
function setInfoByHostname(
string _hostname,
bytes _data
) onlyAuthBy0Admin external returns (bool success) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.hostname.', _hostname));
/* Set info. */
return _setInfo(dataId, _data);
}
/**
* Set Info by Owner
*/
function setInfoByOwner(
address _owner,
bytes _data
) onlyAuthBy0Admin external returns (bool success) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.owner.', _owner));
/* Set info. */
return _setInfo(dataId, _data);
}
/**
* Set Info by Regular Expression
*/
function setInfoByRegex(
string _regex,
bytes _data
) onlyAuthBy0Admin external returns (bool success) {
/* Calculate the data id. */
bytes32 dataId = keccak256(abi.encodePacked(
_NAMESPACE, '.regex.', _regex));
/* Set info. */
return _setInfo(dataId, _data);
}
/**
* Set Info
*
* JSON-formatted data, encoded into bytes.
*/
function _setInfo(
bytes32 _dataId,
bytes _data
) private returns (bool success) {
/* Set data. */
_zer0netDb.setBytes(_dataId, _data);
/* Broadcast event. */
emit Filter(_dataId, _data);
/* Return success. */
return true;
}
/**
* Set Successor
*
* This is the contract address that replaced this current instnace.
*/
function setSuccessor(
address _newSuccessor
) onlyAuthBy0Admin external returns (bool success) {
/* Set successor contract. */
_successor = _newSuccessor;
/* Return success. */
return true;
}
/***************************************************************************
*
* INTERFACES
*
*/
/**
* Supports Interface (EIP-165)
*
* (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md)
*
* NOTE: Must support the following conditions:
* 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface)
* 2. (false) when interfaceID is 0xffffffff
* 3. (true) for any other interfaceID this contract implements
* 4. (false) for any other interfaceID
*/
function supportsInterface(
bytes4 _interfaceID
) external pure returns (bool) {
/* Initialize constants. */
bytes4 InvalidId = 0xffffffff;
bytes4 ERC165Id = 0x01ffc9a7;
/* Validate condition #2. */
if (_interfaceID == InvalidId) {
return false;
}
/* Validate condition #1. */
if (_interfaceID == ERC165Id) {
return true;
}
// TODO Add additional interfaces here.
/* Return false (for condition #4). */
return false;
}
/***************************************************************************
*
* UTILITIES
*
*/
/**
* Transfer Any ERC20 Token
*
* @notice Owner can transfer out any accidentally sent ERC20 tokens.
*
* @dev Provides an ERC20 interface, which allows for the recover
* of any accidentally sent ERC20 tokens.
*/
function transferAnyERC20Token(
address _tokenAddress,
uint _tokens
) public onlyOwner returns (bool success) {
return ERC20Interface(_tokenAddress).transfer(owner, _tokens);
}
}
|
Get Info Retrieves the JSON-formatted, byte-encoded data stored at the location of `_dataId`./
|
function _getInfo(
bytes32 _dataId
) private view returns (bytes info) {
info = _zer0netDb.getBytes(_dataId);
| 15,819,306 |
// File: contracts/IRebaser.sol
pragma solidity 0.5.16;
interface IRebaser {
function checkRebase() external;
}
// File: contracts/token/GovernanceStorage.sol
pragma solidity 0.5.16;
/* Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
contract GovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/token/TokenStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.16;
contract TokenStorage {
using SafeMath for uint256;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Total supply of YAMs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10 ** 24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10 ** 18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public auscsScalingFactor;
mapping(address => uint256) internal _auscBalances;
mapping(address => mapping(address => uint256)) internal _allowedFragments;
uint256 public initSupply;
}
// File: contracts/token/TokenInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.16;
contract TokenInterface is TokenStorage, GovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevAuscsScalingFactor, uint256 newAuscsScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/* - ERC20 Events - */
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
event Burn(address from, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
function auscToFragment(uint256 ausc) external view returns (uint256);
function fragmentToAusc(uint256 value) external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
// function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
// File: contracts/token/Governance.sol
pragma solidity 0.5.16;
/* Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
contract GovernanceToken is TokenInterface {
/// @notice An event emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Get delegatee for an address delegating
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "AUSC::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = _auscBalances[delegator]; // balance of underlying YAMs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "AUSC::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
}
// File: @openzeppelin/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: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 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");
}
}
}
// File: contracts/AUSC.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.5.16;
contract AUSCToken is GovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov, "only governance");
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier rebaseAtTheEnd() {
_;
if (msg.sender == tx.origin && rebaser != address(0)) {
IRebaser(rebaser).checkRebase();
}
}
modifier onlyMinter() {
require(
msg.sender == rebaser || msg.sender == gov,
"not minter"
);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(auscsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * auscsScalingFactor
// this is used to check if auscsScalingFactor will be too high to compute balances when rebasing.
return uint256(- 1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 auscValue = fragmentToAusc(amount);
// increase initSupply
initSupply = initSupply.add(auscValue);
// make sure the mint didnt push maxScalingFactor too low
require(auscsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_auscBalances[to] = _auscBalances[to].add(auscValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], auscValue);
emit Mint(to, amount);
emit Transfer(address(0), to, amount);
}
/**
* @notice Burns tokens, decreasing totalSupply, initSupply, and a users balance.
*/
function burn(uint256 amount)
external
returns (bool)
{
_burn(msg.sender, amount);
return true;
}
function _burn(address from, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.sub(amount);
// get underlying value
uint256 auscValue = fragmentToAusc(amount);
// increase initSupply
initSupply = initSupply.sub(auscValue);
// make sure the burn didnt push maxScalingFactor too low
require(auscsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// sub balance, will revert on underflow
_auscBalances[from] = _auscBalances[from].sub(auscValue);
// remove delegates from the minter
_moveDelegates(_delegates[from], address(0), auscValue);
emit Burn(from, amount);
emit Transfer(from, address(0), amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
rebaseAtTheEnd
returns (bool)
{
// underlying balance is stored in auscs, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == auscsScalingFactor / 1e24;
// get amount in underlying
uint256 auscValue = fragmentToAusc(value);
// sub from balance of sender
_auscBalances[msg.sender] = _auscBalances[msg.sender].sub(auscValue);
// add to balance of receiver
_auscBalances[to] = _auscBalances[to].add(auscValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], auscValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
rebaseAtTheEnd
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in auscs
uint256 auscValue = fragmentToAusc(value);
// sub from from
_auscBalances[from] = _auscBalances[from].sub(auscValue);
_auscBalances[to] = _auscBalances[to].add(auscValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], auscValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return auscToFragment(_auscBalances[who]);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _auscBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
rebaseAtTheEnd
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
external
rebaseAtTheEnd
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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)
external
rebaseAtTheEnd
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
// no change
if (indexDelta == 0) {
emit Rebase(epoch, auscsScalingFactor, auscsScalingFactor);
return totalSupply;
}
// for events
uint256 prevAuscsScalingFactor = auscsScalingFactor;
if (!positive) {
// negative rebase, decrease scaling factor
auscsScalingFactor = auscsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
// positive reabse, increase scaling factor
uint256 newScalingFactor = auscsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
auscsScalingFactor = newScalingFactor;
} else {
auscsScalingFactor = _maxScalingFactor();
}
}
// update total supply, correctly
totalSupply = auscToFragment(initSupply);
emit Rebase(epoch, prevAuscsScalingFactor, auscsScalingFactor);
return totalSupply;
}
function auscToFragment(uint256 ausc)
public
view
returns (uint256)
{
return ausc.mul(auscsScalingFactor).div(internalDecimals);
}
function fragmentToAusc(uint256 value)
public
view
returns (uint256)
{
return value.mul(internalDecimals).div(auscsScalingFactor);
}
// Rescue tokens
function rescueTokens(
address token,
address to,
uint256 amount
)
external
onlyGov
returns (bool)
{
// transfer to
SafeERC20.safeTransfer(IERC20(token), to, amount);
return true;
}
}
contract AUSC is AUSCToken {
constructor() public {}
/**
* @notice Initialize the new money market
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initTotalSupply_
)
public
{
super.initialize(name_, symbol_, decimals_);
auscsScalingFactor = BASE;
initSupply = fragmentToAusc(initTotalSupply_);
totalSupply = initTotalSupply_;
_auscBalances[initial_owner] = initSupply;
gov = initial_owner;
}
}
|
Computes the current max scaling factor/
|
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
| 15,276,737 |
./full_match/44787/0x82D062DE292987581e348a5Edb1011321DEA994B/sources/project_/contracts/CASProject.sol
|
Get project parameters bytesParams ( project_address: bytes(address) ) `projectAddress` parameter must be passed in bytes and opened in the contract as the required type return projectId Returns `projectId`, `startDate`, `endDate` of a given project return startDate Returns `projectId`, `startDate`, `endDate` of a given project return endDate Returns `projectId`, `startDate`, `endDate` of a given project/
|
function getProject(bytes[] memory bytesParams) external view
returns(uint projectId, uint startDate, uint endDate) {
address projectAddress = BytesLib.toAddress(bytesParams[0], 0);
return (projects[projectAddress].projectId, projects[projectAddress].startDate, projects[projectAddress].endDate);
}
| 13,263,959 |
./full_match/44787/0x635Cfb967a7B37957e7f9A71d8C681b2868f45Af/sources/contracts/CyberBoxMarketPlace.sol
|
Set partner address and profit share _tokenCreaterAddress Token creater address/ function setTokenCreaterAddressAndProfitShare(address _tokenCreaterAddress, uint8 _partnerSharePercentage) require( _partnerSharePercentage > 0 && _partnerSharePercentage <= 100, "Allowed percentage range is 1 to 100" ); partnerSharePercentage = _partnerSharePercentage;
|
function setTokenCreaterAddressAndProfitShare(address _tokenCreaterAddress)
external
onlyDev
{
require(tokenCreaterAddress == address(0), "Owner can't change partner address once it's set");
require(_tokenCreaterAddress != address(0), "Can't set to address 0x0");
tokenCreaterAddress = _tokenCreaterAddress;
}
| 13,254,383 |
pragma solidity 0.4.24;
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;
}
}
interface ArbiterInterface {
function getOndutyOracle() external returns(address, string);
function score(uint data) external returns (uint);
}
// Arbiter contract is used to get the current chainlink oracle id
contract Arbiter is ArbiterInterface{
using SafeMath for uint256;
// chainlink oracleAddress => jobID , every oracle only put one jobID which parse to string
mapping(address => string) public oraclesAndJobIDs;
// ETH Super Node address => oracleAddress
mapping(bytes32 => address) public superNodeAndOracles;
// ETH Super Node pub key keccak256 hash existence map
mapping(bytes32 => bool) public superNodes;
// current on duty super node pub key keccak256 hash
bytes32[] public onDutySuperNodes;
// valid on duty oracles
uint public validOracles;
// on duty oracles hash
bytes32 public updateHash;
// on duty oracle
address public currentOracle;
// on duty oracle job id
string public currentJobId;
// request nonce
uint256 public nonce;
function getOracleIndex() private returns(uint256){
nonce = nonce.add(1);
uint256 previousBlock = block.number.sub(1);
bytes32 hash = keccak256(blockhash(previousBlock),previousBlock,msg.sender,nonce);
return uint256(uint8(hash));
}
// get current on duty oraces
function getOndutyOracle() external returns(address, string){
refresh();
bytes32 addr = onDutySuperNodes[getOracleIndex().mod(validOracles)];
address oracle = superNodeAndOracles[addr];
if (oracle == 0x0) {
for (uint i=0;i<validOracles;i++) {
addr = onDutySuperNodes[i];
oracle = superNodeAndOracles[addr];
if(oracle != 0x0){
break;
}
}
}
require(oracle != 0x0,"no super node has been registered");
string storage jobId = oraclesAndJobIDs[oracle];
currentOracle = oracle;
currentJobId = jobId;
return (oracle,jobId);
}
function score(uint data) external returns (uint){
//TODO to be implemented
return data;
}
function registerArbiter(string publicKey, address oracle, string jobId, string signature) public {
bytes32 oracleHash = keccak256(oracle);
bytes32 jobIdHash = keccak256(jobId);
bytes memory mergeHash = mergeBytes(oracleHash,jobIdHash);
string memory data = toHex(mergeHash);
require(p256_verify(publicKey,data,signature) == true,"verify signature error");
refresh();
bytes memory pubKeyBytes = hexStr2bytes(publicKey);
bytes32 keyHash = keccak256(pubKeyBytes);
// require(superNodes[keyHash] == true , "sender must be one of the super node account");
superNodeAndOracles[keyHash] = oracle;
oraclesAndJobIDs[oracle] = jobId;
}
function refresh() public {
uint validAddressLength = 36;
bytes32[36] memory p;
uint input;
assembly {
if iszero(staticcall(gas, 20, input, 0x00, p, 0x480)) {
revert(0,0)
}
}
for (uint i = 0;i<p.length;i++){
if (p[i] == 0x0 && validAddressLength == 36){
validAddressLength = i;
}
}
bytes32 newHash = keccak256(abi.encodePacked(p));
if (updateHash != newHash ){
updateHash = newHash;
onDutySuperNodes = p;
validOracles = validAddressLength;
for (uint j=0;j<p.length;j++){
bytes32 node = p[j];
if (superNodes[node] == false) {
superNodes[node] = true;
}
}
}
}
function p256_verify(string pubkey, string data, string sig) public view returns(bool) {
string memory i = strConcat(strConcat(pubkey, data), sig);
bytes memory input = hexStr2bytes(i);
uint256[1] memory p;
assembly {
if iszero(staticcall(gas, 21, input, 193, p, 0x20)) {
revert(0,0)
}
}
return p[0] == 1;
}
function strConcat(string _a, string _b) internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ret = new string(_ba.length + _bb.length);
bytes memory bret = bytes(ret);
uint k = 0;
for (uint i = 0; i < _ba.length; i++)bret[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bret[k++] = _bb[i];
return string(ret);
}
function hexStr2bytes(string data) internal returns (bytes){
bytes memory a = bytes(data);
uint[] memory b = new uint[](a.length);
for (uint i = 0; i < a.length; i++) {
uint _a = uint(a[i]);
if (_a > 96) {
b[i] = _a - 97 + 10;
}
else if (_a > 66) {
b[i] = _a - 65 + 10;
}
else {
b[i] = _a - 48;
}
}
bytes memory c = new bytes(b.length / 2);
for (uint _i = 0; _i < b.length; _i += 2) {
c[_i / 2] = byte(b[_i] * 16 + b[_i + 1]);
}
return c;
}
function toHex(bytes origin) returns(string) {
bytes memory dst = new bytes(2 * origin.length);
bytes memory hextable = "0123456789abcdef";
uint j = 0;
for (uint i= 0; i<origin.length;i++ ) {
dst[j] = hextable[uint256(origin[i])>>4];
dst[j+1] = hextable[uint256(origin[i])&0x0f];
j = j+ 2;
}
return string(dst);
}
function mergeBytes(bytes32 first,bytes32 second) returns(bytes) {
bytes memory merged = new bytes(first.length + second.length);
uint k = 0;
for (i = 0; i < first.length; i++) {
merged[k] = first[i];
k++;
}
for (uint i = 0; i < second.length; i++) {
merged[k] = second[i];
k++;
}
return merged;
}
}
|
TODO to be implemented
|
function score(uint data) external returns (uint){
return data;
}
| 15,852,168 |
/**
*Submitted for verification at Etherscan.io on 2021-08-02
*/
// File: @sygnum/solidity-base-contracts/contracts/helpers/Initializable.sol
pragma solidity 0.5.12;
/**
* @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,
"Initializable: Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
// solhint-disable-next-line
assembly {
cs := extcodesize(address)
}
return cs == 0;
}
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @sygnum/solidity-base-contracts/contracts/role/interface/IBaseOperators.sol
/**
* @title IBaseOperators
* @notice Interface for BaseOperators contract
*/
pragma solidity 0.5.12;
interface IBaseOperators {
function isOperator(address _account) external view returns (bool);
function isAdmin(address _account) external view returns (bool);
function isSystem(address _account) external view returns (bool);
function isRelay(address _account) external view returns (bool);
function isMultisig(address _contract) external view returns (bool);
function confirmFor(address _address) external;
function addOperator(address _account) external;
function removeOperator(address _account) external;
function addAdmin(address _account) external;
function removeAdmin(address _account) external;
function addSystem(address _account) external;
function removeSystem(address _account) external;
function addRelay(address _account) external;
function removeRelay(address _account) external;
function addOperatorAndAdmin(address _account) external;
function removeOperatorAndAdmin(address _account) external;
}
// File: @sygnum/solidity-base-contracts/contracts/role/base/Operatorable.sol
/**
* @title Operatorable
* @author Team 3301 <[email protected]>
* @dev Operatorable contract stores the BaseOperators contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract Operatorable is Initializable {
IBaseOperators internal operatorsInst;
address private operatorsPending;
event OperatorsContractChanged(address indexed caller, address indexed operatorsAddress);
event OperatorsContractPending(address indexed caller, address indexed operatorsAddress);
/**
* @dev Reverts if sender does not have operator role associated.
*/
modifier onlyOperator() {
require(isOperator(msg.sender), "Operatorable: caller does not have the operator role");
_;
}
/**
* @dev Reverts if sender does not have admin role associated.
*/
modifier onlyAdmin() {
require(isAdmin(msg.sender), "Operatorable: caller does not have the admin role");
_;
}
/**
* @dev Reverts if sender does not have system role associated.
*/
modifier onlySystem() {
require(isSystem(msg.sender), "Operatorable: caller does not have the system role");
_;
}
/**
* @dev Reverts if sender does not have multisig privileges.
*/
modifier onlyMultisig() {
require(isMultisig(msg.sender), "Operatorable: caller does not have multisig role");
_;
}
/**
* @dev Reverts if sender does not have admin or system role associated.
*/
modifier onlyAdminOrSystem() {
require(isAdminOrSystem(msg.sender), "Operatorable: caller does not have the admin role nor system");
_;
}
/**
* @dev Reverts if sender does not have operator or system role associated.
*/
modifier onlyOperatorOrSystem() {
require(isOperatorOrSystem(msg.sender), "Operatorable: caller does not have the operator role nor system");
_;
}
/**
* @dev Reverts if sender does not have the relay role associated.
*/
modifier onlyRelay() {
require(isRelay(msg.sender), "Operatorable: caller does not have relay role associated");
_;
}
/**
* @dev Reverts if sender does not have relay or operator role associated.
*/
modifier onlyOperatorOrRelay() {
require(
isOperator(msg.sender) || isRelay(msg.sender),
"Operatorable: caller does not have the operator role nor relay"
);
_;
}
/**
* @dev Reverts if sender does not have relay or admin role associated.
*/
modifier onlyAdminOrRelay() {
require(
isAdmin(msg.sender) || isRelay(msg.sender),
"Operatorable: caller does not have the admin role nor relay"
);
_;
}
/**
* @dev Reverts if sender does not have the operator, or system, or relay role associated.
*/
modifier onlyOperatorOrSystemOrRelay() {
require(
isOperator(msg.sender) || isSystem(msg.sender) || isRelay(msg.sender),
"Operatorable: caller does not have the operator role nor system nor relay"
);
_;
}
/**
* @dev Initialization instead of constructor, called once. The setOperatorsContract function can be called only by Admin role with
* confirmation through the operators contract.
* @param _baseOperators BaseOperators contract address.
*/
function initialize(address _baseOperators) public initializer {
_setOperatorsContract(_baseOperators);
}
/**
* @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case
* @param _baseOperators BaseOperators contract address.
*/
function setOperatorsContract(address _baseOperators) public onlyAdmin {
require(_baseOperators != address(0), "Operatorable: address of new operators contract can not be zero");
operatorsPending = _baseOperators;
emit OperatorsContractPending(msg.sender, _baseOperators);
}
/**
* @dev The function should be called from new operators contract by admin to ensure that operatorsPending address
* is the real contract address.
*/
function confirmOperatorsContract() public {
require(operatorsPending != address(0), "Operatorable: address of new operators contract can not be zero");
require(msg.sender == operatorsPending, "Operatorable: should be called from new operators contract");
_setOperatorsContract(operatorsPending);
}
/**
* @return The address of the BaseOperators contract.
*/
function getOperatorsContract() public view returns (address) {
return address(operatorsInst);
}
/**
* @return The pending address of the BaseOperators contract.
*/
function getOperatorsPending() public view returns (address) {
return operatorsPending;
}
/**
* @return If '_account' has operator privileges.
*/
function isOperator(address _account) public view returns (bool) {
return operatorsInst.isOperator(_account);
}
/**
* @return If '_account' has admin privileges.
*/
function isAdmin(address _account) public view returns (bool) {
return operatorsInst.isAdmin(_account);
}
/**
* @return If '_account' has system privileges.
*/
function isSystem(address _account) public view returns (bool) {
return operatorsInst.isSystem(_account);
}
/**
* @return If '_account' has relay privileges.
*/
function isRelay(address _account) public view returns (bool) {
return operatorsInst.isRelay(_account);
}
/**
* @return If '_contract' has multisig privileges.
*/
function isMultisig(address _contract) public view returns (bool) {
return operatorsInst.isMultisig(_contract);
}
/**
* @return If '_account' has admin or system privileges.
*/
function isAdminOrSystem(address _account) public view returns (bool) {
return (operatorsInst.isAdmin(_account) || operatorsInst.isSystem(_account));
}
/**
* @return If '_account' has operator or system privileges.
*/
function isOperatorOrSystem(address _account) public view returns (bool) {
return (operatorsInst.isOperator(_account) || operatorsInst.isSystem(_account));
}
/** INTERNAL FUNCTIONS */
function _setOperatorsContract(address _baseOperators) internal {
require(_baseOperators != address(0), "Operatorable: address of new operators contract cannot be zero");
operatorsInst = IBaseOperators(_baseOperators);
emit OperatorsContractChanged(msg.sender, _baseOperators);
}
}
// File: zos-lib/contracts/upgradeability/Proxy.sol
pragma solidity ^0.5.0;
/**
* @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());
}
}
// File: zos-lib/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library ZOSLibAddress {
/**
* 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) }
return size > 0;
}
}
// File: zos-lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title BaseUpgradeabilityProxy
* @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 BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed 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 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @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) internal {
require(ZOSLibAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
// File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
// File: zos-lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @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) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
// File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(_admin);
}
}
// File: contracts/token/SygnumTokenProxy.sol
/**
* @title SygnumTokenProxy
* @author Team 3301 <[email protected]>
* @dev Proxies SygnumToken calls and enables SygnumToken upgradability.
*/
pragma solidity 0.5.12;
contract SygnumTokenProxy is AdminUpgradeabilityProxy {
/* solhint-disable no-empty-blocks */
constructor(
address implementation,
address proxyOwnerAddr,
bytes memory data
) public AdminUpgradeabilityProxy(implementation, proxyOwnerAddr, data) {}
/* solhint-enable no-empty-blocks */
}
// File: contracts/factory/ProxyDeployer.sol
/**
* @title ProxyDeployer
* @author Team 3301 <[email protected]>
* @dev Library to deploy a proxy instance for a Sygnum.
*/
pragma solidity 0.5.12;
library ProxyDeployer {
/**
* @dev Deploy the proxy instance and initialize it
* @param _tokenImplementation Address of the logic contract
* @param _proxyAdmin Address of the admin for the proxy
* @param _data Bytecode needed for initialization
* @return address New instance address
*/
function deployTokenProxy(
address _tokenImplementation,
address _proxyAdmin,
bytes memory _data
) public returns (address) {
SygnumTokenProxy proxy = new SygnumTokenProxy(_tokenImplementation, _proxyAdmin, _data);
return address(proxy);
}
}
// File: contracts/token/ERC20/ERC20Detailed.sol
/**
* @title ERC20Detailed
* @author OpenZeppelin-Solidity = "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol", and rmeoval
* of IERC20 due to " contract binary not set. Can't deploy new instance.
* This contract may be abstract, not implement an abstract parent's methods completely
* or not invoke an inherited contract's constructor correctly"
*/
pragma solidity 0.5.12;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed {
string internal _name;
string internal _symbol;
uint8 internal _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 that 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;
}
}
// File: contracts/token/ERC20/ERC20SygnumDetailed.sol
/**
* @title ERC20SygnumDetailed
* @author Team 3301 <[email protected]>
* @dev ERC20 Standard Token with additional details and role set.
*/
pragma solidity 0.5.12;
contract ERC20SygnumDetailed is ERC20Detailed, Operatorable {
bytes4 private _category;
string private _class;
address private _issuer;
event NameUpdated(address issuer, string name, address token);
event SymbolUpdated(address issuer, string symbol, address token);
event CategoryUpdated(address issuer, bytes4 category, address token);
event ClassUpdated(address issuer, string class, address token);
event IssuerUpdated(address issuer, address newIssuer, address token);
/**
* @dev Sets the values for `name`, `symbol`, `decimals`, `category`, `class` and `issuer`. All are
* mutable apart from `issuer`, which is immutable.
* @param name string
* @param symbol string
* @param decimals uint8
* @param category bytes4
* @param class string
* @param issuer address
*/
function _setDetails(
string memory name,
string memory symbol,
uint8 decimals,
bytes4 category,
string memory class,
address issuer
) internal {
_name = name;
_symbol = symbol;
_decimals = decimals;
_category = category;
_class = class;
_issuer = issuer;
}
/**
* @dev Returns the category of the token.
*/
function category() public view returns (bytes4) {
return _category;
}
/**
* @dev Returns the class of the token.
*/
function class() public view returns (string memory) {
return _class;
}
/**
* @dev Returns the issuer of the token.
*/
function issuer() public view returns (address) {
return _issuer;
}
/**
* @dev Updates the name of the token, only callable by Sygnum operator.
* @param name_ The new name.
*/
function updateName(string memory name_) public onlyOperator {
_name = name_;
emit NameUpdated(msg.sender, _name, address(this));
}
/**
* @dev Updates the symbol of the token, only callable by Sygnum operator.
* @param symbol_ The new symbol.
*/
function updateSymbol(string memory symbol_) public onlyOperator {
_symbol = symbol_;
emit SymbolUpdated(msg.sender, symbol_, address(this));
}
/**
* @dev Updates the category of the token, only callable by Sygnum operator.
* @param category_ The new cateogry.
*/
function updateCategory(bytes4 category_) public onlyOperator {
_category = category_;
emit CategoryUpdated(msg.sender, _category, address(this));
}
/**
* @dev Updates the class of the token, only callable by Sygnum operator.
* @param class_ The new class.
*/
function updateClass(string memory class_) public onlyOperator {
_class = class_;
emit ClassUpdated(msg.sender, _class, address(this));
}
/**
* @dev Updates issuer ownership, only callable by Sygnum operator.
* @param issuer_ The new issuer.
*/
function updateIssuer(address issuer_) public onlyOperator {
_issuer = issuer_;
emit IssuerUpdated(msg.sender, _issuer, address(this));
}
}
// File: openzeppelin-solidity/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: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Overload/ERC20.sol
pragma solidity 0.5.12;
/**
* @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;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @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, "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 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, "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 {
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, "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 {
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, "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 {
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, "ERC20: burn amount exceeds allowance")
);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/interface/IWhitelist.sol
pragma solidity 0.5.12;
/**
* @title IWhitelist
* @notice Interface for Whitelist contract
*/
contract IWhitelist {
function isWhitelisted(address _account) external view returns (bool);
function toggleWhitelist(address _account, bool _toggled) external;
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/instance/Whitelistable.sol
/**
* @title Whitelistable
* @author Team 3301 <[email protected]>
* @dev Whitelistable contract stores the Whitelist contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract Whitelistable is Initializable, Operatorable {
IWhitelist internal whitelistInst;
address private whitelistPending;
event WhitelistContractChanged(address indexed caller, address indexed whitelistAddress);
event WhitelistContractPending(address indexed caller, address indexed whitelistAddress);
/**
* @dev Reverts if _account is not whitelisted.
* @param _account address to determine if whitelisted.
*/
modifier whenWhitelisted(address _account) {
require(isWhitelisted(_account), "Whitelistable: account is not whitelisted");
_;
}
/**
* @dev Initialization instead of constructor, called once. The setWhitelistContract function can be called only by Admin role with
* confirmation through the whitelist contract.
* @param _whitelist Whitelist contract address.
* @param _baseOperators BaseOperators contract address.
*/
function initialize(address _baseOperators, address _whitelist) public initializer {
_setOperatorsContract(_baseOperators);
_setWhitelistContract(_whitelist);
}
/**
* @dev Set the new the address of Whitelist contract, should be confirmed from whitelist contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case
* @param _whitelist Whitelist contract address.
*/
function setWhitelistContract(address _whitelist) public onlyAdmin {
require(_whitelist != address(0), "Whitelistable: address of new whitelist contract can not be zero");
whitelistPending = _whitelist;
emit WhitelistContractPending(msg.sender, _whitelist);
}
/**
* @dev The function should be called from new whitelist contract by admin to insure that whitelistPending address
* is the real contract address.
*/
function confirmWhitelistContract() public {
require(whitelistPending != address(0), "Whitelistable: address of new whitelist contract can not be zero");
require(msg.sender == whitelistPending, "Whitelistable: should be called from new whitelist contract");
_setWhitelistContract(whitelistPending);
}
/**
* @return The address of the Whitelist contract.
*/
function getWhitelistContract() public view returns (address) {
return address(whitelistInst);
}
/**
* @return The pending address of the Whitelist contract.
*/
function getWhitelistPending() public view returns (address) {
return whitelistPending;
}
/**
* @return If '_account' is whitelisted.
*/
function isWhitelisted(address _account) public view returns (bool) {
return whitelistInst.isWhitelisted(_account);
}
/** INTERNAL FUNCTIONS */
function _setWhitelistContract(address _whitelist) internal {
require(_whitelist != address(0), "Whitelistable: address of new whitelist contract cannot be zero");
whitelistInst = IWhitelist(_whitelist);
emit WhitelistContractChanged(msg.sender, _whitelist);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Whitelist.sol
/**
* @title ERC20Whitelist
* @author Team 3301 <[email protected]>
* @dev Overloading ERC20 functions to ensure that addresses attempting to particular
* actions are whitelisted.
*/
pragma solidity 0.5.12;
contract ERC20Whitelist is ERC20, Whitelistable {
/**
* @dev Overload transfer function to validate sender and receiver are whitelisted.
* @param to address that recieves the funds.
* @param value amount of funds.
*/
function transfer(address to, uint256 value) public whenWhitelisted(msg.sender) whenWhitelisted(to) returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Overload approve function to validate sender and spender are whitelisted.
* @param spender address that can spend the funds.
* @param value amount of funds.
*/
function approve(address spender, uint256 value)
public
whenWhitelisted(msg.sender)
whenWhitelisted(spender)
returns (bool)
{
return super.approve(spender, value);
}
/**
* @dev Overload transferFrom function to validate sender, from and receiver are whitelisted.
* @param from address that funds will be transferred from.
* @param to address that funds will be transferred to.
* @param value amount of funds.
*/
function transferFrom(
address from,
address to,
uint256 value
) public whenWhitelisted(msg.sender) whenWhitelisted(from) whenWhitelisted(to) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Overload increaseAllowance validate sender and spender are whitelisted.
* @param spender address that will be allowed to transfer funds.
* @param addedValue amount of funds to added to current allowance.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
whenWhitelisted(spender)
whenWhitelisted(msg.sender)
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Overload decreaseAllowance validate sender and spender are whitelisted.
* @param spender address that will be allowed to transfer funds.
* @param subtractedValue amount of funds to be deducted to current allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenWhitelisted(spender)
whenWhitelisted(msg.sender)
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Overload _burn function to ensure that account has been whitelisted.
* @param account address that funds will be burned from.
* @param value amount of funds that will be burned.
*/
function _burn(address account, uint256 value) internal whenWhitelisted(account) {
super._burn(account, value);
}
/**
* @dev Overload _burnFrom function to ensure sender and account have been whitelisted.
* @param account address that funds will be burned from allowance.
* @param amount amount of funds that will be burned.
*/
function _burnFrom(address account, uint256 amount) internal whenWhitelisted(msg.sender) whenWhitelisted(account) {
super._burnFrom(account, amount);
}
/**
* @dev Overload _mint function to ensure account has been whitelisted.
* @param account address that funds will be minted to.
* @param amount amount of funds that will be minted.
*/
function _mint(address account, uint256 amount) internal whenWhitelisted(account) {
super._mint(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/role/interface/ITraderOperators.sol
/**
* @title ITraderOperators
* @notice Interface for TraderOperators contract
*/
pragma solidity 0.5.12;
contract ITraderOperators {
function isTrader(address _account) external view returns (bool);
function addTrader(address _account) external;
function removeTrader(address _account) external;
}
// File: @sygnum/solidity-base-contracts/contracts/role/trader/TraderOperatorable.sol
/**
* @title TraderOperatorable
* @author Team 3301 <[email protected]>
* @dev TraderOperatorable contract stores TraderOperators contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract TraderOperatorable is Operatorable {
ITraderOperators internal traderOperatorsInst;
address private traderOperatorsPending;
event TraderOperatorsContractChanged(address indexed caller, address indexed traderOperatorsAddress);
event TraderOperatorsContractPending(address indexed caller, address indexed traderOperatorsAddress);
/**
* @dev Reverts if sender does not have the trader role associated.
*/
modifier onlyTrader() {
require(isTrader(msg.sender), "TraderOperatorable: caller is not trader");
_;
}
/**
* @dev Reverts if sender does not have the operator or trader role associated.
*/
modifier onlyOperatorOrTraderOrSystem() {
require(
isOperator(msg.sender) || isTrader(msg.sender) || isSystem(msg.sender),
"TraderOperatorable: caller is not trader or operator or system"
);
_;
}
/**
* @dev Initialization instead of constructor, called once. The setTradersOperatorsContract function can be called only by Admin role with
* confirmation through the operators contract.
* @param _baseOperators BaseOperators contract address.
* @param _traderOperators TraderOperators contract address.
*/
function initialize(address _baseOperators, address _traderOperators) public initializer {
super.initialize(_baseOperators);
_setTraderOperatorsContract(_traderOperators);
}
/**
* @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case
* @param _traderOperators TradeOperators contract address.
*/
function setTraderOperatorsContract(address _traderOperators) public onlyAdmin {
require(
_traderOperators != address(0),
"TraderOperatorable: address of new traderOperators contract can not be zero"
);
traderOperatorsPending = _traderOperators;
emit TraderOperatorsContractPending(msg.sender, _traderOperators);
}
/**
* @dev The function should be called from new operators contract by admin to insure that traderOperatorsPending address
* is the real contract address.
*/
function confirmTraderOperatorsContract() public {
require(
traderOperatorsPending != address(0),
"TraderOperatorable: address of pending traderOperators contract can not be zero"
);
require(
msg.sender == traderOperatorsPending,
"TraderOperatorable: should be called from new traderOperators contract"
);
_setTraderOperatorsContract(traderOperatorsPending);
}
/**
* @return The address of the TraderOperators contract.
*/
function getTraderOperatorsContract() public view returns (address) {
return address(traderOperatorsInst);
}
/**
* @return The pending TraderOperators contract address
*/
function getTraderOperatorsPending() public view returns (address) {
return traderOperatorsPending;
}
/**
* @return If '_account' has trader privileges.
*/
function isTrader(address _account) public view returns (bool) {
return traderOperatorsInst.isTrader(_account);
}
/** INTERNAL FUNCTIONS */
function _setTraderOperatorsContract(address _traderOperators) internal {
require(
_traderOperators != address(0),
"TraderOperatorable: address of new traderOperators contract can not be zero"
);
traderOperatorsInst = ITraderOperators(_traderOperators);
emit TraderOperatorsContractChanged(msg.sender, _traderOperators);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/Pausable.sol
/**
* @title Pausable
* @author Team 3301 <[email protected]>
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account in the TraderOperatorable
* contract.
*/
pragma solidity 0.5.12;
contract Pausable is TraderOperatorable {
event Paused(address indexed account);
event Unpaused(address indexed account);
bool internal _paused;
constructor() internal {
_paused = false;
}
/**
* @dev Reverts if contract is paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Reverts if contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by operator to pause child contract. The contract
* must not already be paused.
*/
function pause() public onlyOperatorOrTraderOrSystem whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/** @dev Called by operator to pause child contract. The contract
* must already be paused.
*/
function unpause() public onlyOperatorOrTraderOrSystem whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
/**
* @return If child contract is already paused or not.
*/
function isPaused() public view returns (bool) {
return _paused;
}
/**
* @return If child contract is not paused.
*/
function isNotPaused() public view returns (bool) {
return !_paused;
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Pausable.sol
/**
* @title ERC20Pausable
* @author Team 3301 <[email protected]>
* @dev Overloading ERC20 functions to ensure that the contract has not been paused.
*/
pragma solidity 0.5.12;
contract ERC20Pausable is ERC20, Pausable {
/**
* @dev Overload transfer function to ensure contract has not been paused.
* @param to address that recieves the funds.
* @param value amount of funds.
*/
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Overload approve function to ensure contract has not been paused.
* @param spender address that can spend the funds.
* @param value amount of funds.
*/
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
/**
* @dev Overload transferFrom function to ensure contract has not been paused.
* @param from address that funds will be transferred from.
* @param to address that funds will be transferred to.
* @param value amount of funds.
*/
function transferFrom(
address from,
address to,
uint256 value
) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Overload increaseAllowance function to ensure contract has not been paused.
* @param spender address that will be allowed to transfer funds.
* @param addedValue amount of funds to added to current allowance.
*/
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Overload decreaseAllowance function to ensure contract has not been paused.
* @param spender address that will be allowed to transfer funds.
* @param subtractedValue amount of funds to be deducted to current allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Overload _burn function to ensure contract has not been paused.
* @param account address that funds will be burned from.
* @param value amount of funds that will be burned.
*/
function _burn(address account, uint256 value) internal whenNotPaused {
super._burn(account, value);
}
/**
* @dev Overload _burnFrom function to ensure contract has not been paused.
* @param account address that funds will be burned from allowance.
* @param amount amount of funds that will be burned.
*/
function _burnFrom(address account, uint256 amount) internal whenNotPaused {
super._burnFrom(account, amount);
}
/**
* @dev Overload _mint function to ensure contract has not been paused.
* @param account address that funds will be minted to.
* @param amount amount of funds that will be minted.
*/
function _mint(address account, uint256 amount) internal whenNotPaused {
super._mint(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Mintable.sol
/**
* @title ERC20Mintable
* @author Team 3301 <[email protected]>
* @dev For blocking and unblocking particular user funds.
*/
pragma solidity 0.5.12;
contract ERC20Mintable is ERC20, Operatorable {
/**
* @dev Overload _mint to ensure only operator or system can mint funds.
* @param account address that will recieve new funds.
* @param amount of funds to be minted.
*/
function _mint(address account, uint256 amount) internal onlyOperatorOrSystem {
require(amount > 0, "ERC20Mintable: amount has to be greater than 0");
super._mint(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Snapshot.sol
/**
* @title ERC20Snapshot
* @author Team 3301 <[email protected]>
* @notice Records historical balances.
*/
pragma solidity 0.5.12;
contract ERC20Snapshot is ERC20 {
using SafeMath for uint256;
/**
* @dev `Snapshot` 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 Snapshot {
uint256 fromBlock; // `fromBlock` is the block number at which the value was generated from
uint256 value; // `value` is the amount of tokens at a specific block number
}
/**
* @dev `_snapshotBalances` 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 => Snapshot[]) private _snapshotBalances;
// Tracks the history of the `totalSupply` of the token
Snapshot[] private _snapshotTotalSupply;
/**
* @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, uint256 _blockNumber) public view returns (uint256) {
return getValueAt(_snapshotBalances[_owner], _blockNumber);
}
/**
* @dev 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(uint256 _blockNumber) public view returns (uint256) {
return getValueAt(_snapshotTotalSupply, _blockNumber);
}
/**
* @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(Snapshot[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) {
return checkpoints[checkpoints.length.sub(1)].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min;
uint256 max = checkpoints.length.sub(1);
while (max > min) {
uint256 mid = (max.add(min).add(1)).div(2);
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid.sub(1);
}
}
return checkpoints[min].value;
}
/**
* @dev `updateValueAtNow` used to update the `_snapshotBalances` map and the `_snapshotTotalSupply`
* @param checkpoints The history of data being updated
* @param _value The new number of tokens
*/
function updateValueAtNow(Snapshot[] storage checkpoints, uint256 _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) {
checkpoints.push(Snapshot(block.number, _value));
} else {
checkpoints[checkpoints.length.sub(1)].value = _value;
}
}
/**
* @dev Internal function that transfers an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param to The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function transfer(address to, uint256 value) public returns (bool result) {
result = super.transfer(to, value);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[msg.sender], balanceOf(msg.sender));
updateValueAtNow(_snapshotBalances[to], balanceOf(to));
}
/**
* @dev Internal function that transfers an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param from The account that funds will be taken from.
* @param to The account that funds will be given too.
* @param value The amount of funds to be transferred..
*/
function transferFrom(
address from,
address to,
uint256 value
) public returns (bool result) {
result = super.transferFrom(from, to, value);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[from], balanceOf(from));
updateValueAtNow(_snapshotBalances[to], balanceOf(to));
}
/**
* @dev Internal function that confiscates an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param confiscatee The account that funds will be taken from.
* @param receiver The account that funds will be given too.
* @param amount The amount of funds to be transferred..
*/
function _confiscate(
address confiscatee,
address receiver,
uint256 amount
) internal {
super._transfer(confiscatee, receiver, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[confiscatee], balanceOf(confiscatee));
updateValueAtNow(_snapshotBalances[receiver], balanceOf(receiver));
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
super._mint(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
super._burn(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFor(address account, uint256 amount) internal {
super._burn(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
super._burnFrom(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Burnable.sol
/**
* @title ERC20Burnable
* @author Team 3301 <[email protected]>
* @dev For burning funds from particular user addresses.
*/
pragma solidity 0.5.12;
contract ERC20Burnable is ERC20Snapshot, Operatorable {
/**
* @dev Overload ERC20 _burnFor, burning funds from a particular users address.
* @param account address to burn funds from.
* @param amount of funds to burn.
*/
function _burnFor(address account, uint256 amount) internal onlyOperator {
super._burn(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/Freezable.sol
/**
* @title Freezable
* @author Team 3301 <[email protected]>
* @dev Freezable contract to freeze functionality for particular addresses. Freezing/unfreezing is controlled
* by operators in Operatorable contract which is initialized with the relevant BaseOperators address.
*/
pragma solidity 0.5.12;
contract Freezable is Operatorable {
mapping(address => bool) public frozen;
event FreezeToggled(address indexed account, bool frozen);
/**
* @dev Reverts if address is empty.
* @param _address address to validate.
*/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "Freezable: Empty address");
_;
}
/**
* @dev Reverts if account address is frozen.
* @param _account address to validate is not frozen.
*/
modifier whenNotFrozen(address _account) {
require(!frozen[_account], "Freezable: account is frozen");
_;
}
/**
* @dev Reverts if account address is not frozen.
* @param _account address to validate is frozen.
*/
modifier whenFrozen(address _account) {
require(frozen[_account], "Freezable: account is not frozen");
_;
}
/**
* @dev Getter to determine if address is frozen.
* @param _account address to determine if frozen or not.
* @return bool is frozen
*/
function isFrozen(address _account) public view returns (bool) {
return frozen[_account];
}
/**
* @dev Toggle freeze/unfreeze on _account address, with _toggled being true/false.
* @param _account address to toggle.
* @param _toggled freeze/unfreeze.
*/
function toggleFreeze(address _account, bool _toggled) public onlyValidAddress(_account) onlyOperator {
frozen[_account] = _toggled;
emit FreezeToggled(_account, _toggled);
}
/**
* @dev Batch freeze/unfreeze multiple addresses, with _toggled being true/false.
* @param _addresses address array.
* @param _toggled freeze/unfreeze.
*/
function batchToggleFreeze(address[] memory _addresses, bool _toggled) public {
require(_addresses.length <= 256, "Freezable: batch count is greater than 256");
for (uint256 i = 0; i < _addresses.length; i++) {
toggleFreeze(_addresses[i], _toggled);
}
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Freezable.sol
/**
* @title ERC20Freezable
* @author Team 3301 <[email protected]>
* @dev Overloading ERC20 functions to ensure client addresses are not frozen for particular actions.
*/
pragma solidity 0.5.12;
contract ERC20Freezable is ERC20, Freezable {
/**
* @dev Overload transfer function to ensure sender and receiver have not been frozen.
* @param to address that recieves the funds.
* @param value amount of funds.
*/
function transfer(address to, uint256 value) public whenNotFrozen(msg.sender) whenNotFrozen(to) returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Overload approve function to ensure sender and receiver have not been frozen.
* @param spender address that can spend the funds.
* @param value amount of funds.
*/
function approve(address spender, uint256 value)
public
whenNotFrozen(msg.sender)
whenNotFrozen(spender)
returns (bool)
{
return super.approve(spender, value);
}
/**
* @dev Overload transferFrom function to ensure sender, approver and receiver have not been frozen.
* @param from address that funds will be transferred from.
* @param to address that funds will be transferred to.
* @param value amount of funds.
*/
function transferFrom(
address from,
address to,
uint256 value
) public whenNotFrozen(msg.sender) whenNotFrozen(from) whenNotFrozen(to) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Overload increaseAllowance function to ensure sender and spender have not been frozen.
* @param spender address that will be allowed to transfer funds.
* @param addedValue amount of funds to added to current allowance.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
whenNotFrozen(msg.sender)
whenNotFrozen(spender)
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Overload decreaseAllowance function to ensure sender and spender have not been frozen.
* @param spender address that will be allowed to transfer funds.
* @param subtractedValue amount of funds to be deducted to current allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenNotFrozen(msg.sender)
whenNotFrozen(spender)
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Overload _burnfrom function to ensure sender and user to be burned from have not been frozen.
* @param account account that funds will be burned from.
* @param amount amount of funds to be burned.
*/
function _burnFrom(address account, uint256 amount) internal whenNotFrozen(msg.sender) whenNotFrozen(account) {
super._burnFrom(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Destroyable.sol
/**
* @title ERC20Destroyable
* @author Team 3301 <[email protected]>
* @notice Allows operator to destroy contract.
*/
pragma solidity 0.5.12;
contract ERC20Destroyable is Operatorable {
event Destroyed(address indexed caller, address indexed account, address indexed contractAddress);
function destroy(address payable to) public onlyOperator {
emit Destroyed(msg.sender, to, address(this));
selfdestruct(to);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Tradeable.sol
/**
* @title ERC20Tradeable
* @author Team 3301 <[email protected]>
* @dev Trader accounts can approve particular addresses on behalf of a user.
*/
pragma solidity 0.5.12;
contract ERC20Tradeable is ERC20, TraderOperatorable {
/**
* @dev Trader can approve users balance to a particular address for a particular amount.
* @param _owner address that approves the funds.
* @param _spender address that spends the funds.
* @param _value amount of funds.
*/
function approveOnBehalf(
address _owner,
address _spender,
uint256 _value
) public onlyTrader {
super._approve(_owner, _spender, _value);
}
}
// File: @sygnum/solidity-base-contracts/contracts/role/interface/IBlockerOperators.sol
/**
* @title IBlockerOperators
* @notice Interface for BlockerOperators contract
*/
pragma solidity 0.5.12;
contract IBlockerOperators {
function isBlocker(address _account) external view returns (bool);
function addBlocker(address _account) external;
function removeBlocker(address _account) external;
}
// File: @sygnum/solidity-base-contracts/contracts/role/blocker/BlockerOperatorable.sol
/**
* @title BlockerOperatorable
* @author Team 3301 <[email protected]>
* @dev BlockerOperatorable contract stores BlockerOperators contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract BlockerOperatorable is Operatorable {
IBlockerOperators internal blockerOperatorsInst;
address private blockerOperatorsPending;
event BlockerOperatorsContractChanged(address indexed caller, address indexed blockerOperatorAddress);
event BlockerOperatorsContractPending(address indexed caller, address indexed blockerOperatorAddress);
/**
* @dev Reverts if sender does not have the blocker role associated.
*/
modifier onlyBlocker() {
require(isBlocker(msg.sender), "BlockerOperatorable: caller is not blocker role");
_;
}
/**
* @dev Reverts if sender does not have the blocker or operator role associated.
*/
modifier onlyBlockerOrOperator() {
require(
isBlocker(msg.sender) || isOperator(msg.sender),
"BlockerOperatorable: caller is not blocker or operator role"
);
_;
}
/**
* @dev Initialization instead of constructor, called once. The setBlockerOperatorsContract function can be called only by Admin role with
* confirmation through the operators contract.
* @param _baseOperators BaseOperators contract address.
* @param _blockerOperators BlockerOperators contract address.
*/
function initialize(address _baseOperators, address _blockerOperators) public initializer {
super.initialize(_baseOperators);
_setBlockerOperatorsContract(_blockerOperators);
}
/**
* @dev Set the new the address of BlockerOperators contract, should be confirmed from BlockerOperators contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case.
* @param _blockerOperators BlockerOperators contract address.
*/
function setBlockerOperatorsContract(address _blockerOperators) public onlyAdmin {
require(
_blockerOperators != address(0),
"BlockerOperatorable: address of new blockerOperators contract can not be zero."
);
blockerOperatorsPending = _blockerOperators;
emit BlockerOperatorsContractPending(msg.sender, _blockerOperators);
}
/**
* @dev The function should be called from new BlockerOperators contract by admin to insure that blockerOperatorsPending address
* is the real contract address.
*/
function confirmBlockerOperatorsContract() public {
require(
blockerOperatorsPending != address(0),
"BlockerOperatorable: address of pending blockerOperators contract can not be zero"
);
require(
msg.sender == blockerOperatorsPending,
"BlockerOperatorable: should be called from new blockerOperators contract"
);
_setBlockerOperatorsContract(blockerOperatorsPending);
}
/**
* @return The address of the BlockerOperators contract.
*/
function getBlockerOperatorsContract() public view returns (address) {
return address(blockerOperatorsInst);
}
/**
* @return The pending BlockerOperators contract address
*/
function getBlockerOperatorsPending() public view returns (address) {
return blockerOperatorsPending;
}
/**
* @return If '_account' has blocker privileges.
*/
function isBlocker(address _account) public view returns (bool) {
return blockerOperatorsInst.isBlocker(_account);
}
/** INTERNAL FUNCTIONS */
function _setBlockerOperatorsContract(address _blockerOperators) internal {
require(
_blockerOperators != address(0),
"BlockerOperatorable: address of new blockerOperators contract can not be zero"
);
blockerOperatorsInst = IBlockerOperators(_blockerOperators);
emit BlockerOperatorsContractChanged(msg.sender, _blockerOperators);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Blockable.sol
/**
* @title ERC20Blockable
* @author Team 3301 <[email protected]>
* @dev For blocking and unblocking particular user funds.
*/
pragma solidity 0.5.12;
contract ERC20Blockable is ERC20, BlockerOperatorable {
uint256 public totalBlockedBalance;
mapping(address => uint256) public _blockedBalances;
event Blocked(address indexed blocker, address indexed account, uint256 value);
event UnBlocked(address indexed blocker, address indexed account, uint256 value);
/**
* @dev Block funds, and move funds from _balances into _blockedBalances.
* @param _account address to block funds.
* @param _amount of funds to block.
*/
function block(address _account, uint256 _amount) public onlyBlockerOrOperator {
_balances[_account] = _balances[_account].sub(_amount);
_blockedBalances[_account] = _blockedBalances[_account].add(_amount);
totalBlockedBalance = totalBlockedBalance.add(_amount);
emit Blocked(msg.sender, _account, _amount);
}
/**
* @dev Unblock funds, and move funds from _blockedBalances into _balances.
* @param _account address to unblock funds.
* @param _amount of funds to unblock.
*/
function unblock(address _account, uint256 _amount) public onlyBlockerOrOperator {
_balances[_account] = _balances[_account].add(_amount);
_blockedBalances[_account] = _blockedBalances[_account].sub(_amount);
totalBlockedBalance = totalBlockedBalance.sub(_amount);
emit UnBlocked(msg.sender, _account, _amount);
}
/**
* @dev Getter for the amount of blocked balance for a particular address.
* @param _account address to get blocked balance.
* @return amount of blocked balance.
*/
function blockedBalanceOf(address _account) public view returns (uint256) {
return _blockedBalances[_account];
}
/**
* @dev Getter for the total amount of blocked funds for all users.
* @return amount of total blocked balance.
*/
function getTotalBlockedBalance() public view returns (uint256) {
return totalBlockedBalance;
}
}
// File: contracts/token/SygnumToken.sol
/**
* @title SygnumToken
* @author Team 3301 <[email protected]>
* @notice ERC20 token with additional features.
*/
pragma solidity 0.5.12;
contract SygnumToken is
ERC20Snapshot,
ERC20SygnumDetailed,
ERC20Pausable,
ERC20Mintable,
ERC20Whitelist,
ERC20Tradeable,
ERC20Blockable,
ERC20Burnable,
ERC20Freezable,
ERC20Destroyable
{
event Minted(address indexed minter, address indexed account, uint256 value);
event Burned(address indexed burner, uint256 value);
event BurnedFor(address indexed burner, address indexed account, uint256 value);
event Confiscated(address indexed account, uint256 amount, address indexed receiver);
uint16 internal constant BATCH_LIMIT = 256;
/**
* @dev Initialize contracts.
* @param _baseOperators Base operators contract address.
* @param _whitelist Whitelist contract address.
* @param _traderOperators Trader operators contract address.
* @param _blockerOperators Blocker operators contract address.
*/
function initializeContractsAndConstructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes4 _category,
string memory _class,
address _issuer,
address _baseOperators,
address _whitelist,
address _traderOperators,
address _blockerOperators
) public initializer {
super.initialize(_baseOperators);
_setWhitelistContract(_whitelist);
_setTraderOperatorsContract(_traderOperators);
_setBlockerOperatorsContract(_blockerOperators);
_setDetails(_name, _symbol, _decimals, _category, _class, _issuer);
}
/**
* @dev Burn.
* @param _amount Amount of tokens to burn.
*/
function burn(uint256 _amount) public {
require(!isFrozen(msg.sender), "SygnumToken: Account must not be frozen.");
super._burn(msg.sender, _amount);
emit Burned(msg.sender, _amount);
}
/**
* @dev BurnFor.
* @param _account Address to burn tokens for.
* @param _amount Amount of tokens to burn.
*/
function burnFor(address _account, uint256 _amount) public {
super._burnFor(_account, _amount);
emit BurnedFor(msg.sender, _account, _amount);
}
/**
* @dev BurnFrom.
* @param _account Address to burn tokens from.
* @param _amount Amount of tokens to burn.
*/
function burnFrom(address _account, uint256 _amount) public {
super._burnFrom(_account, _amount);
emit Burned(_account, _amount);
}
/**
* @dev Mint.
* @param _account Address to mint tokens to.
* @param _amount Amount to mint.
*/
function mint(address _account, uint256 _amount) public {
if (isSystem(msg.sender)) {
require(!isFrozen(_account), "SygnumToken: Account must not be frozen if system calling.");
}
super._mint(_account, _amount);
emit Minted(msg.sender, _account, _amount);
}
/**
* @dev Confiscate.
* @param _confiscatee Account to confiscate funds from.
* @param _receiver Account to transfer confiscated funds to.
* @param _amount Amount of tokens to confiscate.
*/
function confiscate(
address _confiscatee,
address _receiver,
uint256 _amount
) public onlyOperator whenNotPaused whenWhitelisted(_receiver) whenWhitelisted(_confiscatee) {
super._confiscate(_confiscatee, _receiver, _amount);
emit Confiscated(_confiscatee, _amount, _receiver);
}
/**
* @dev Batch burn for.
* @param _amounts Array of all values to burn.
* @param _accounts Array of all addresses to burn from.
*/
function batchBurnFor(address[] memory _accounts, uint256[] memory _amounts) public {
require(_accounts.length == _amounts.length, "SygnumToken: values and recipients are not equal.");
require(_accounts.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for (uint256 i = 0; i < _accounts.length; i++) {
burnFor(_accounts[i], _amounts[i]);
}
}
/**
* @dev Batch mint.
* @param _accounts Array of all addresses to mint to.
* @param _amounts Array of all values to mint.
*/
function batchMint(address[] memory _accounts, uint256[] memory _amounts) public {
require(_accounts.length == _amounts.length, "SygnumToken: values and recipients are not equal.");
require(_accounts.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for (uint256 i = 0; i < _accounts.length; i++) {
mint(_accounts[i], _amounts[i]);
}
}
/**
* @dev Batch confiscate to a maximum of 256 addresses.
* @param _confiscatees array of addresses whose funds are being confiscated
* @param _receivers array of addresses who's receiving the funds
* @param _values array of values of funds being confiscated
*/
function batchConfiscate(
address[] memory _confiscatees,
address[] memory _receivers,
uint256[] memory _values
) public returns (bool) {
require(
_confiscatees.length == _values.length && _receivers.length == _values.length,
"SygnumToken: confiscatees, recipients and values are not equal."
);
require(_confiscatees.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for (uint256 i = 0; i < _confiscatees.length; i++) {
confiscate(_confiscatees[i], _receivers[i], _values[i]);
}
}
}
// File: contracts/token/upgrade/prd/SygnumTokenV1.sol
/**
* @title MetadataUpgrade
* @author Team 3301 <[email protected]>
* @dev Upgraded SygnumToken. This upgrade adds the "tokenURI" field, which can hold a link to off chain token metadata.
*/
pragma solidity 0.5.12;
contract SygnumTokenV1 is SygnumToken {
string public tokenURI;
bool public initializedV1;
event TokenUriUpdated(string newToken);
// changed back to public for tests
function initializeContractsAndConstructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes4 _category,
string memory _class,
address _issuer,
address _baseOperators,
address _whitelist,
address _traderOperators,
address _blockerOperators,
string memory _tokenURI
) public {
require(!initializedV1, "SygnumTokenV1: already initialized");
super.initializeContractsAndConstructor(
_name,
_symbol,
_decimals,
_category,
_class,
_issuer,
_baseOperators,
_whitelist,
_traderOperators,
_blockerOperators
);
initializeV1(_tokenURI);
}
function initializeV1(string memory _tokenURI) public {
require(!initializedV1, "SygnumTokenV1: already initialized");
tokenURI = _tokenURI;
initializedV1 = true;
}
function updateTokenURI(string memory _newToken) public onlyOperator {
tokenURI = _newToken;
emit TokenUriUpdated(_newToken);
}
}
// File: contracts/factory/Details.sol
/**
* @title Details
* @author Team 3301 <[email protected]>
* @notice Shared library for Sygnum token details struct.
*/
pragma solidity 0.5.12;
library Details {
struct TokenDetails {
string name;
string symbol;
uint8 decimals;
bytes4 category;
string class;
address issuer;
string tokenURI;
}
}
// File: contracts/factory/TokenDeployer.sol
/**
* @title TokenDeployer
* @author Team 3301 <[email protected]>
* @dev Library to deploy and initialize a new instance of Sygnum Equity Token.
* This is commonly used by a TokenFactory to automatically deploy and configure
*/
pragma experimental ABIEncoderV2;
pragma solidity 0.5.12;
library TokenDeployer {
/**
* @dev Initialize a token contracts.
* @param _proxy Address of the proxy
* @param _baseOperators Address of the base operator role contract
* @param _whitelist Address of the whitelist contract
* @param _traderOperators Address of the trader operator role contract
* @param _blockerOperators Address of the blocker operator role contract
* @param _details token details as defined by the TokenDetails struct
*/
function initializeToken(
address _proxy,
address _baseOperators,
address _whitelist,
address _traderOperators,
address _blockerOperators,
Details.TokenDetails memory _details
) public {
SygnumTokenV1(_proxy).initializeContractsAndConstructor(
_details.name,
_details.symbol,
_details.decimals,
_details.category,
_details.class,
_details.issuer,
_baseOperators,
_whitelist,
_traderOperators,
_blockerOperators,
_details.tokenURI
);
}
}
// File: contracts/factory/TokenFactory.sol
/**
* @title TokenFactory
* @author Team 3301 <[email protected]>
* @dev Token factory to be used by operators to deploy arbitrary Sygnum Equity Token.
*/
pragma solidity 0.5.12;
contract TokenFactory is Initializable, Operatorable {
address public whitelist;
address public proxyAdmin;
address public implementation;
address public traderOperators;
address public blockerOperators;
event UpdatedWhitelist(address indexed whitelist);
event UpdatedTraderOperators(address indexed traderOperators);
event UpdatedBlockerOperators(address indexed blockerOperators);
event UpdatedProxyAdmin(address indexed proxyAdmin);
event UpdatedImplementation(address indexed implementation);
event NewTokenDeployed(address indexed issuer, address token, address proxy);
/**
* @dev Initialization instead of constructor, called once. Sets BaseOperators contract through pausable contract
* resulting in use of Operatorable contract within this contract.
* @param _baseOperators BaseOperators contract address.
* @param _traderOperators TraderOperators contract address.
* @param _blockerOperators BlockerOperators contract address.
* @param _whitelist Whitelist contract address.
*/
function initialize(
address _baseOperators,
address _traderOperators,
address _blockerOperators,
address _whitelist,
address _implementation,
address _proxyAdmin
) public initializer {
require(_baseOperators != address(0), "TokenFactory: _baseOperators cannot be set to an empty address");
require(_traderOperators != address(0), "TokenFactory: _traderOperators cannot be set to an empty address");
require(_blockerOperators != address(0), "TokenFactory: _blockerOperators cannot be set to an empty address");
require(_whitelist != address(0), "TokenFactory: _whitelist cannot be set to an empty address");
require(_implementation != address(0), "TokenFactory: _implementation cannot be set to an empty address");
require(_proxyAdmin != address(0), "TokenFactory: _proxyAdmin cannot be set to an empty address");
traderOperators = _traderOperators;
blockerOperators = _blockerOperators;
whitelist = _whitelist;
proxyAdmin = _proxyAdmin;
implementation = _implementation;
super.initialize(_baseOperators);
}
/**
* @dev allows operator, system or relay to launch a new token with a new name, symbol, decimals, category, and issuer.
* Defaults to using whitelist stored in this contract. If _whitelist is address(0), else it will use
* _whitelist as the param to pass into the new token's constructor upon deployment
* @param _details token details as defined by the TokenDetails struct
* @param _whitelist address
*/
function newToken(Details.TokenDetails memory _details, address _whitelist)
public
onlyOperatorOrSystemOrRelay
returns (address, address)
{
address whitelistAddress;
_whitelist == address(0) ? whitelistAddress = whitelist : whitelistAddress = _whitelist;
address baseOperators = getOperatorsContract();
address proxy = ProxyDeployer.deployTokenProxy(implementation, proxyAdmin, "");
TokenDeployer.initializeToken(
proxy,
baseOperators,
whitelistAddress,
traderOperators,
blockerOperators,
_details
);
emit NewTokenDeployed(_details.issuer, implementation, proxy);
return (implementation, proxy);
}
/**
* @dev updates the whitelist to be used for future generated tokens
* @param _whitelist address
*/
function updateWhitelist(address _whitelist) public onlyOperator {
require(_whitelist != address(0), "TokenFactory: _whitelist cannot be set to an empty address");
whitelist = _whitelist;
emit UpdatedWhitelist(whitelist);
}
/**
* @dev updates the traderOperators contract address to be used for future generated tokens
* @param _traderOperators address
*/
function updateTraderOperators(address _traderOperators) public onlyOperator {
require(_traderOperators != address(0), "TokenFactory: _traderOperators cannot be set to an empty address");
traderOperators = _traderOperators;
emit UpdatedTraderOperators(_traderOperators);
}
/**
* @dev updates the blockerOperators contract address to be used for future generated tokens
* @param _blockerOperators address
*/
function updateBlockerOperators(address _blockerOperators) public onlyOperator {
require(_blockerOperators != address(0), "TokenFactory: _blockerOperators cannot be set to an empty address");
blockerOperators = _blockerOperators;
emit UpdatedBlockerOperators(_blockerOperators);
}
/**
* @dev update the implementation address used when deploying proxy contracts
* @param _implementation address
*/
function updateImplementation(address _implementation) public onlyOperator {
require(_implementation != address(0), "TokenFactory: _implementation cannot be set to an empty address");
implementation = _implementation;
emit UpdatedImplementation(implementation);
}
/**
* @dev update the proxy admin address used when deploying proxy contracts
* @param _proxyAdmin address
*/
function updateProxyAdmin(address _proxyAdmin) public {
require(_proxyAdmin != address(0), "TokenFactory: _proxyAdmin cannot be set to an empty address");
require(msg.sender == proxyAdmin, "TokenFactory: caller not proxy admin");
proxyAdmin = _proxyAdmin;
emit UpdatedProxyAdmin(proxyAdmin);
}
}
|
Initialization instead of constructor, called once. The setWhitelistContract function can be called only by Admin role with confirmation through the whitelist contract. _whitelist Whitelist contract address. _baseOperators BaseOperators contract address./
|
function initialize(address _baseOperators, address _whitelist) public initializer {
_setOperatorsContract(_baseOperators);
_setWhitelistContract(_whitelist);
}
| 2,087,946 |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* 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.
*/
// File: @openzeppelin/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: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 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");
}
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/interfaces/IStrategy.sol
pragma solidity 0.5.11;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to Lending platform.
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function liquidate() external;
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
/**
* @dev The address of the reward token for the Strategy.
*/
function rewardTokenAddress() external pure returns (address);
/**
* @dev The threshold (denominated in the reward token) over which the
* vault will auto harvest on allocate calls.
*/
function rewardLiquidationThreshold() external pure returns (uint256);
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
//keccak256("OUSD.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
//keccak256("OUSD.pending.governor");
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: @openzeppelin/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: @openzeppelin/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;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @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, "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 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, "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 {
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, "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 {
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, "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 {
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, "ERC20: burn amount exceeds allowance"));
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @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;
}
}
// File: contracts/utils/InitializableToken.sol
pragma solidity 0.5.11;
contract InitializableToken is ERC20, InitializableERC20Detailed {
/**
* @dev Initialization function for implementing contract
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(string memory _nameArg, string memory _symbolArg)
internal
{
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
contract OUSD is Initializable, InitializableToken, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 public rebasingCredits;
// Exchange rate between internal credits and OUSD
uint256 public rebasingCreditsPerToken;
mapping(address => uint256) private _creditBalances;
// Allowances denominated in OUSD
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingCredits;
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => bool) public rebaseOptInList;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableToken._initialize(_nameArg, _symbolArg);
_totalSupply = 0;
rebasingCredits = 0;
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
nonRebasingCredits = 0;
nonRebasingSupply = 0;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
bool isNonRebasingTo = _isNonRebasingAddress(_to);
bool isNonRebasingFrom = _isNonRebasingAddress(_from);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingCredits = nonRebasingCredits.add(creditsCredited);
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingCredits = nonRebasingCredits.sub(creditsDeducted);
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
} else if (isNonRebasingTo && isNonRebasingFrom) {
// Transfer between two non rebasing accounts. They may have
// different exchange rates so update the count of non rebasing
// credits with the difference
nonRebasingCredits =
nonRebasingCredits +
creditsCredited -
creditsDeducted;
}
// Make sure the fixed credits per token get set for to/from accounts if
// they have not been
if (isNonRebasingTo && nonRebasingCreditsPerToken[_to] == 0) {
nonRebasingCreditsPerToken[_to] = rebasingCreditsPerToken;
}
if (isNonRebasingFrom && nonRebasingCreditsPerToken[_from] == 0) {
nonRebasingCreditsPerToken[_from] = rebasingCreditsPerToken;
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @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)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
return _mint(_account, _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), "Mint to the zero address");
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
bool isNonRebasingAccount = _isNonRebasingAddress(_account);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
if (nonRebasingCreditsPerToken[_account] == 0) {
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
}
nonRebasingCredits = nonRebasingCredits.add(creditAmount);
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
_totalSupply = _totalSupply.add(_amount);
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
return _burn(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), "Burn from the zero address");
bool isNonRebasingAccount = _isNonRebasingAddress(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
_totalSupply = _totalSupply.sub(_amount);
if (isNonRebasingAccount) {
nonRebasingCredits = nonRebasingCredits.sub(creditAmount);
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits.sub(creditAmount);
}
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an accounts balance non rebasing, i.e. does not alter with rebases
* @param _account Address of the account.
*/
function _isNonRebasingAddress(address _account)
internal
view
returns (bool)
{
return Address.isContract(_account) && !rebaseOptInList[_account];
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public {
require(_isNonRebasingAddress(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
nonRebasingCredits = nonRebasingCredits.sub(
_creditBalances[msg.sender]
);
_creditBalances[msg.sender] = newCreditBalance;
rebaseOptInList[msg.sender] = true;
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public {
require(!_isNonRebasingAddress(msg.sender), "Account has not opted in");
nonRebasingCredits = nonRebasingCredits.add(
_creditBalances[msg.sender]
);
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
delete rebaseOptInList[msg.sender];
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
returns (uint256)
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return _totalSupply;
}
_totalSupply = _newTotalSupply;
if (_totalSupply > MAX_SUPPLY) _totalSupply = MAX_SUPPLY;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return _totalSupply;
}
}
// File: contracts/interfaces/IBasicToken.sol
pragma solidity 0.5.11;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/utils/Helpers.sol
pragma solidity 0.5.11;
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// File: contracts/vault/VaultStorage.sol
pragma solidity 0.5.11;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event StrategyAdded(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event StrategyWeightsUpdated(
address[] _strategyAddresses,
uint256[] weights
);
event DepositsPaused();
event DepositsUnpaused();
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies supported by the Vault
struct Strategy {
bool isSupported;
uint256 targetWeight; // 18 decimals. 100% = 1e18
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public depositPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address public rebaseHooksAddr = address(0);
// Address of Uniswap
address public uniswapAddr = address(0);
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address pf the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// File: contracts/interfaces/IMinMaxOracle.sol
pragma solidity 0.5.11;
interface IMinMaxOracle {
//Assuming 8 decimals
function priceMin(string calldata symbol) external returns (uint256);
function priceMax(string calldata symbol) external returns (uint256);
}
interface IViewMinMaxOracle {
function priceMin(string calldata symbol) external view returns (uint256);
function priceMax(string calldata symbol) external view returns (uint256);
}
// File: contracts/interfaces/IRebaseHooks.sol
pragma solidity 0.5.11;
interface IRebaseHooks {
function postRebase(bool sync) external;
}
// File: contracts/interfaces/IVault.sol
pragma solidity 0.5.11;
interface IVault {
event AssetSupported(address _asset);
event StrategyAdded(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event StrategyWeightsUpdated(
address[] _strategyAddresses,
uint256[] weights
);
event DepositsPaused();
event DepositsUnpaused();
// Governable.sol
function transferGovernance(address _newGovernor) external;
function claimGovernance() external;
function governor() external view returns (address);
// VaultAdmin.sol
function setPriceProvider(address _priceProvider) external;
function priceProvider() external view returns (address);
function setRedeemFeeBps(uint256 _redeemFeeBps) external;
function redeemFeeBps() external view returns (uint256);
function setVaultBuffer(uint256 _vaultBuffer) external;
function vaultBuffer() external view returns (uint256);
function setAutoAllocateThreshold(uint256 _threshold) external;
function autoAllocateThreshold() external view returns (uint256);
function setRebaseThreshold(uint256 _threshold) external;
function rebaseThreshold() external view returns (uint256);
function setRebaseHooksAddr(address _address) external;
function rebaseHooksAddr() external view returns (address);
function setUniswapAddr(address _address) external;
function uniswapAddr() external view returns (address);
function supportAsset(address _asset) external;
function addStrategy(address _addr, uint256 _targetWeight) external;
function removeStrategy(address _addr) external;
function setStrategyWeights(
address[] calldata _strategyAddresses,
uint256[] calldata _weights
) external;
function pauseRebase() external;
function unpauseRebase() external;
function rebasePaused() external view returns (bool);
function pauseDeposits() external;
function unpauseDeposits() external;
function depositPaused() external view returns (bool);
function transferToken(address _asset, uint256 _amount) external;
function harvest() external;
function harvest(address _strategyAddr) external;
function priceUSDMint(string calldata symbol) external returns (uint256);
function priceUSDRedeem(string calldata symbol) external returns (uint256);
// VaultCore.sol
function mint(address _asset, uint256 _amount) external;
function mintMultiple(
address[] calldata _assets,
uint256[] calldata _amount
) external;
function redeem(uint256 _amount) external;
function redeemAll() external;
function allocate() external;
function rebase() external returns (uint256);
function checkBalance() external view returns (uint256);
function checkBalance(address _asset) external view returns (uint256);
function calculateRedeemOutputs(uint256 _amount)
external
returns (uint256[] memory);
function getAssetCount() external view returns (uint256);
function getAllAssets() external view returns (address[] memory);
function getStrategyCount() external view returns (uint256);
function isSupportedAsset(address _asset) external view returns (bool);
}
// File: contracts/vault/VaultCore.sol
pragma solidity 0.5.11;
/**
* @title OUSD Vault Contract
* @notice The Vault contract stores assets. On a deposit, OUSD will be minted
and sent to the depositor. On a withdrawal, OUSD will be burned and
assets will be sent to the withdrawer. The Vault accepts deposits of
interest form yield bearing strategies which will modify the supply
of OUSD.
* @author Origin Protocol Inc
*/
contract VaultCore is VaultStorage {
uint256 constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/**
* @dev Verifies that the rebasing is not paused.
*/
modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
/**
* @dev Verifies that the deposits are not paused.
*/
modifier whenNotDepositPaused() {
require(!depositPaused, "Deposits paused");
_;
}
/**
* @dev Deposit a supported asset and mint OUSD.
* @param _asset Address of the asset being deposited
* @param _amount Amount of the asset being deposited
*/
function mint(address _asset, uint256 _amount)
external
whenNotDepositPaused
{
require(assets[_asset].isSupported, "Asset is not supported");
require(_amount > 0, "Amount must be greater than 0");
uint256 price = IMinMaxOracle(priceProvider).priceMin(
Helpers.getSymbol(_asset)
);
if (price > 1e8) {
price = 1e8;
}
uint256 priceAdjustedDeposit = _amount.mulTruncateScale(
price.scaleBy(int8(10)), // 18-8 because oracles have 8 decimals precision
10**Helpers.getDecimals(_asset)
);
// Rebase must happen before any transfers occur.
if (priceAdjustedDeposit > rebaseThreshold && !rebasePaused) {
rebase(true);
}
// Transfer the deposited coins to the vault
IERC20 asset = IERC20(_asset);
asset.safeTransferFrom(msg.sender, address(this), _amount);
// Mint matching OUSD
oUSD.mint(msg.sender, priceAdjustedDeposit);
emit Mint(msg.sender, priceAdjustedDeposit);
if (priceAdjustedDeposit >= autoAllocateThreshold) {
allocate();
}
}
/**
* @dev Mint for multiple assets in the same call.
* @param _assets Addresses of assets being deposited
* @param _amounts Amount of each asset at the same index in the _assets
* to deposit.
*/
function mintMultiple(
address[] calldata _assets,
uint256[] calldata _amounts
) external whenNotDepositPaused {
require(_assets.length == _amounts.length, "Parameter length mismatch");
uint256 priceAdjustedTotal = 0;
uint256[] memory assetPrices = _getAssetPrices(false);
for (uint256 i = 0; i < allAssets.length; i++) {
for (uint256 j = 0; j < _assets.length; j++) {
if (_assets[j] == allAssets[i]) {
if (_amounts[j] > 0) {
uint256 assetDecimals = Helpers.getDecimals(
allAssets[i]
);
uint256 price = assetPrices[i];
if (price > 1e18) {
price = 1e18;
}
priceAdjustedTotal += _amounts[j].mulTruncateScale(
price,
10**assetDecimals
);
}
}
}
}
// Rebase must happen before any transfers occur.
if (priceAdjustedTotal > rebaseThreshold && !rebasePaused) {
rebase(true);
}
for (uint256 i = 0; i < _assets.length; i++) {
IERC20 asset = IERC20(_assets[i]);
asset.safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
oUSD.mint(msg.sender, priceAdjustedTotal);
emit Mint(msg.sender, priceAdjustedTotal);
if (priceAdjustedTotal >= autoAllocateThreshold) {
allocate();
}
}
/**
* @dev Withdraw a supported asset and burn OUSD.
* @param _amount Amount of OUSD to burn
*/
function redeem(uint256 _amount) public {
if (_amount > rebaseThreshold && !rebasePaused) {
rebase(false);
}
_redeem(_amount);
}
function _redeem(uint256 _amount) internal {
require(_amount > 0, "Amount must be greater than 0");
// Calculate redemption outputs
uint256[] memory outputs = _calculateRedeemOutputs(_amount);
// Send outputs
for (uint256 i = 0; i < allAssets.length; i++) {
if (outputs[i] == 0) continue;
IERC20 asset = IERC20(allAssets[i]);
if (asset.balanceOf(address(this)) >= outputs[i]) {
// Use Vault funds first if sufficient
asset.safeTransfer(msg.sender, outputs[i]);
} else {
address strategyAddr = _selectWithdrawStrategyAddr(
allAssets[i],
outputs[i]
);
if (strategyAddr != address(0)) {
// Nothing in Vault, but something in Strategy, send from there
IStrategy strategy = IStrategy(strategyAddr);
strategy.withdraw(msg.sender, allAssets[i], outputs[i]);
} else {
// Cant find funds anywhere
revert("Liquidity error");
}
}
}
oUSD.burn(msg.sender, _amount);
// Until we can prove that we won't affect the prices of our assets
// by withdrawing them, this should be here.
// It's possible that a strategy was off on its asset total, perhaps
// a reward token sold for more or for less than anticipated.
if (_amount > rebaseThreshold && !rebasePaused) {
rebase(true);
}
emit Redeem(msg.sender, _amount);
}
/**
* @notice Withdraw a supported asset and burn all OUSD.
*/
function redeemAll() external {
//unfortunately we have to do balanceOf twice
if (oUSD.balanceOf(msg.sender) > rebaseThreshold && !rebasePaused) {
rebase(false);
}
_redeem(oUSD.balanceOf(msg.sender));
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function allocate() public {
_allocate();
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function _allocate() internal {
uint256 vaultValue = _totalValueInVault();
// Nothing in vault to allocate
if (vaultValue == 0) return;
uint256 strategiesValue = _totalValueInStrategies();
// We have a method that does the same as this, gas optimisation
uint256 totalValue = vaultValue + strategiesValue;
// We want to maintain a buffer on the Vault so calculate a percentage
// modifier to multiply each amount being allocated by to enforce the
// vault buffer
uint256 vaultBufferModifier;
if (strategiesValue == 0) {
// Nothing in Strategies, allocate 100% minus the vault buffer to
// strategies
vaultBufferModifier = 1e18 - vaultBuffer;
} else {
vaultBufferModifier = vaultBuffer.mul(totalValue).div(vaultValue);
if (1e18 > vaultBufferModifier) {
// E.g. 1e18 - (1e17 * 10e18)/5e18 = 8e17
// (5e18 * 8e17) / 1e18 = 4e18 allocated from Vault
vaultBufferModifier = 1e18 - vaultBufferModifier;
} else {
// We need to let the buffer fill
return;
}
}
if (vaultBufferModifier == 0) return;
// Iterate over all assets in the Vault and allocate the the appropriate
// strategy
for (uint256 i = 0; i < allAssets.length; i++) {
IERC20 asset = IERC20(allAssets[i]);
uint256 assetBalance = asset.balanceOf(address(this));
// No balance, nothing to do here
if (assetBalance == 0) continue;
// Multiply the balance by the vault buffer modifier and truncate
// to the scale of the asset decimals
uint256 allocateAmount = assetBalance.mulTruncate(
vaultBufferModifier
);
// Get the target Strategy to maintain weightings
address depositStrategyAddr = _selectDepositStrategyAddr(
address(asset),
allocateAmount
);
if (depositStrategyAddr != address(0) && allocateAmount > 0) {
IStrategy strategy = IStrategy(depositStrategyAddr);
// Transfer asset to Strategy and call deposit method to
// mint or take required action
asset.safeTransfer(address(strategy), allocateAmount);
strategy.deposit(address(asset), allocateAmount);
}
}
// Harvest for all reward tokens above reward liquidation threshold
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
uint256 liquidationThreshold = strategy.rewardLiquidationThreshold();
if (liquidationThreshold == 0) {
// No threshold set, always harvest from strategy
IVault(address(this)).harvest(allStrategies[i]);
} else {
// Check balance against liquidation threshold
// Note some strategies don't hold the reward token balance
// on their contract so the liquidation threshold should be
// set to 0
IERC20 rewardToken = IERC20(rewardTokenAddress);
uint256 rewardTokenAmount = rewardToken.balanceOf(
allStrategies[i]
);
if (rewardTokenAmount >= liquidationThreshold) {
IVault(address(this)).harvest(allStrategies[i]);
}
}
}
}
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of oUSD
*/
function rebase() public whenNotRebasePaused returns (uint256) {
rebase(true);
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of oUSD
*/
function rebase(bool sync) internal whenNotRebasePaused returns (uint256) {
if (oUSD.totalSupply() == 0) return 0;
uint256 oldTotalSupply = oUSD.totalSupply();
uint256 newTotalSupply = _totalValue();
// Only rachet upwards
if (newTotalSupply > oldTotalSupply) {
oUSD.changeSupply(newTotalSupply);
if (rebaseHooksAddr != address(0)) {
IRebaseHooks(rebaseHooksAddr).postRebase(sync);
}
}
}
/**
* @dev Determine the total value of assets held by the vault and its
* strategies.
* @return uint256 value Total value in USD (1e18)
*/
function totalValue() external view returns (uint256 value) {
value = _totalValue();
}
/**
* @dev Internal Calculate the total value of the assets held by the
* vault and its strategies.
* @return uint256 value Total value in USD (1e18)
*/
function _totalValue() internal view returns (uint256 value) {
return _totalValueInVault() + _totalValueInStrategies();
}
/**
* @dev Internal to calculate total value of all assets held in Vault.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInVault() internal view returns (uint256 value) {
value = 0;
for (uint256 y = 0; y < allAssets.length; y++) {
IERC20 asset = IERC20(allAssets[y]);
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
uint256 balance = asset.balanceOf(address(this));
if (balance > 0) {
value += balance.scaleBy(int8(18 - assetDecimals));
}
}
}
/**
* @dev Internal to calculate total value of all assets held in Strategies.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategies() internal view returns (uint256 value) {
value = 0;
for (uint256 i = 0; i < allStrategies.length; i++) {
value += _totalValueInStrategy(allStrategies[i]);
}
}
/**
* @dev Internal to calculate total value of all assets held by strategy.
* @param _strategyAddr Address of the strategy
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategy(address _strategyAddr)
internal
view
returns (uint256 value)
{
value = 0;
IStrategy strategy = IStrategy(_strategyAddr);
for (uint256 y = 0; y < allAssets.length; y++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
if (strategy.supportsAsset(allAssets[y])) {
uint256 balance = strategy.checkBalance(allAssets[y]);
if (balance > 0) {
value += balance.scaleBy(int8(18 - assetDecimals));
}
}
}
}
/**
* @dev Calculate difference in percent of asset allocation for a
strategy.
* @param _strategyAddr Address of the strategy
* @return unt256 Difference between current and target. 18 decimals.
* NOTE: This is relative value! not the actual percentage
*/
function _strategyWeightDifference(
address _strategyAddr,
address _asset,
uint256 _modAmount,
bool deposit
) internal view returns (uint256 difference) {
// Since we are comparing relative weights, we should scale by weight so
// that even small weights will be triggered, ie 1% versus 20%
uint256 weight = strategies[_strategyAddr].targetWeight;
if (weight == 0) return 0;
uint256 assetDecimals = Helpers.getDecimals(_asset);
difference =
MAX_UINT -
(
deposit
? _totalValueInStrategy(_strategyAddr).add(
_modAmount.scaleBy(int8(18 - assetDecimals))
)
: _totalValueInStrategy(_strategyAddr).sub(
_modAmount.scaleBy(int8(18 - assetDecimals))
)
)
.divPrecisely(weight);
}
/**
* @dev Select a strategy for allocating an asset to.
* @param _asset Address of asset
* @return address Address of the target strategy
*/
function _selectDepositStrategyAddr(address _asset, uint256 depositAmount)
internal
view
returns (address depositStrategyAddr)
{
depositStrategyAddr = address(0);
uint256 maxDifference = 0;
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (strategy.supportsAsset(_asset)) {
uint256 diff = _strategyWeightDifference(
allStrategies[i],
_asset,
depositAmount,
true
);
if (diff >= maxDifference) {
maxDifference = diff;
depositStrategyAddr = allStrategies[i];
}
}
}
}
/**
* @dev Select a strategy for withdrawing an asset from.
* @param _asset Address of asset
* @return address Address of the target strategy for withdrawal
*/
function _selectWithdrawStrategyAddr(address _asset, uint256 _amount)
internal
view
returns (address withdrawStrategyAddr)
{
withdrawStrategyAddr = address(0);
uint256 minDifference = MAX_UINT;
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (
strategy.supportsAsset(_asset) &&
strategy.checkBalance(_asset) > _amount
) {
uint256 diff = _strategyWeightDifference(
allStrategies[i],
_asset,
_amount,
false
);
if (diff <= minDifference) {
minDifference = diff;
withdrawStrategyAddr = allStrategies[i];
}
}
}
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function checkBalance(address _asset) external view returns (uint256) {
return _checkBalance(_asset);
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function _checkBalance(address _asset)
internal
view
returns (uint256 balance)
{
IERC20 asset = IERC20(_asset);
balance = asset.balanceOf(address(this));
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (strategy.supportsAsset(_asset)) {
balance += strategy.checkBalance(_asset);
}
}
}
/**
* @notice Get the balance of all assets held in Vault and all strategies.
* @return uint256 Balance of all assets (1e18)
*/
function _checkBalance() internal view returns (uint256 balance) {
balance = 0;
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
balance += _checkBalance(allAssets[i]).scaleBy(
int8(18 - assetDecimals)
);
}
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned
*/
function calculateRedeemOutputs(uint256 _amount)
external
returns (uint256[] memory)
{
return _calculateRedeemOutputs(_amount);
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned.
* @return Array of amounts respective to the supported assets
*/
function _calculateRedeemOutputs(uint256 _amount)
internal
returns (uint256[] memory outputs)
{
// We always give out coins in proportion to how many we have,
// Now if all coins were the same value, this math would easy,
// just take the percentage of each coin, and multiply by the
// value to be given out. But if coins are worth more than $1,
// then we would end up handing out too many coins. We need to
// adjust by the total value of coins.
//
// To do this, we total up the value of our coins, by their
// percentages. Then divide what we would otherwise give out by
// this number.
//
// Let say we have 100 DAI at $1.06 and 200 USDT at $1.00.
// So for every 1 DAI we give out, we'll be handing out 2 USDT
// Our total output ratio is: 33% * 1.06 + 66% * 1.00 = 1.02
//
// So when calculating the output, we take the percentage of
// each coin, times the desired output value, divided by the
// totalOutputRatio.
//
// For example, withdrawing: 30 OUSD:
// DAI 33% * 30 / 1.02 = 9.80 DAI
// USDT = 66 % * 30 / 1.02 = 19.60 USDT
//
// Checking these numbers:
// 9.80 DAI * 1.06 = $10.40
// 19.60 USDT * 1.00 = $19.60
//
// And so the user gets $10.40 + $19.60 = $30 worth of value.
uint256 assetCount = getAssetCount();
uint256[] memory assetPrices = _getAssetPrices(true);
uint256[] memory assetBalances = new uint256[](assetCount);
uint256[] memory assetDecimals = new uint256[](assetCount);
uint256 totalBalance = 0;
uint256 totalOutputRatio = 0;
outputs = new uint256[](assetCount);
// Calculate redeem fee
if (redeemFeeBps > 0) {
uint256 redeemFee = _amount.mul(redeemFeeBps).div(10000);
_amount = _amount.sub(redeemFee);
}
// Calculate assets balances and decimals once,
// for a large gas savings.
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 balance = _checkBalance(allAssets[i]);
uint256 decimals = Helpers.getDecimals(allAssets[i]);
assetBalances[i] = balance;
assetDecimals[i] = decimals;
totalBalance += balance.scaleBy(int8(18 - decimals));
}
// Calculate totalOutputRatio
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 price = assetPrices[i];
// Never give out more than one
// stablecoin per dollar of OUSD
if (price < 1e18) {
price = 1e18;
}
uint256 ratio = assetBalances[i]
.scaleBy(int8(18 - assetDecimals[i]))
.mul(price)
.div(totalBalance);
totalOutputRatio += ratio;
}
// Calculate final outputs
uint256 factor = _amount.divPrecisely(totalOutputRatio);
for (uint256 i = 0; i < allAssets.length; i++) {
outputs[i] = assetBalances[i].mul(factor).div(totalBalance);
}
}
/**
* @notice Get an array of the supported asset prices in USD.
* @return uint256[] Array of asset prices in USD (1e18)
*/
function _getAssetPrices(bool useMax)
internal
returns (uint256[] memory assetPrices)
{
assetPrices = new uint256[](getAssetCount());
IMinMaxOracle oracle = IMinMaxOracle(priceProvider);
// Price from Oracle is returned with 8 decimals
// _amount is in assetDecimals
for (uint256 i = 0; i < allAssets.length; i++) {
string memory symbol = Helpers.getSymbol(allAssets[i]);
// Get all the USD prices of the asset in 1e18
if (useMax) {
assetPrices[i] = oracle.priceMax(symbol).scaleBy(int8(18 - 8));
} else {
assetPrices[i] = oracle.priceMin(symbol).scaleBy(int8(18 - 8));
}
}
}
/***************************************
Utils
****************************************/
/**
* @dev Return the number of assets suppported by the Vault.
*/
function getAssetCount() public view returns (uint256) {
return allAssets.length;
}
/**
* @dev Return all asset addresses in order
*/
function getAllAssets() external view returns (address[] memory) {
return allAssets;
}
/**
* @dev Return the number of strategies active on the Vault.
*/
function getStrategyCount() public view returns (uint256) {
return allStrategies.length;
}
function isSupportedAsset(address _asset) external view returns (bool) {
return assets[_asset].isSupported;
}
/**
* @dev Falldown to the admin implementation
* @notice This is a catch all for all functions not declared in core
*/
function() external payable {
bytes32 slot = adminImplPosition;
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, sload(slot), 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)
}
}
}
}
|
Allocate unallocated funds on Vault to strategies. Allocate unallocated funds on Vault to strategies./ Nothing in vault to allocate We have a method that does the same as this, gas optimisation We want to maintain a buffer on the Vault so calculate a percentage modifier to multiply each amount being allocated by to enforce the vault buffer Nothing in Strategies, allocate 100% minus the vault buffer to strategies E.g. 1e18 - (1e17 10e18)/5e18 = 8e17 (5e18 8e17) / 1e18 = 4e18 allocated from Vault We need to let the buffer fill Iterate over all assets in the Vault and allocate the the appropriate strategy No balance, nothing to do here Multiply the balance by the vault buffer modifier and truncate to the scale of the asset decimals Get the target Strategy to maintain weightings Transfer asset to Strategy and call deposit method to mint or take required action Harvest for all reward tokens above reward liquidation threshold No threshold set, always harvest from strategy Check balance against liquidation threshold Note some strategies don't hold the reward token balance on their contract so the liquidation threshold should be set to 0
|
function _allocate() internal {
uint256 vaultValue = _totalValueInVault();
if (vaultValue == 0) return;
uint256 strategiesValue = _totalValueInStrategies();
uint256 totalValue = vaultValue + strategiesValue;
uint256 vaultBufferModifier;
if (strategiesValue == 0) {
vaultBufferModifier = 1e18 - vaultBuffer;
vaultBufferModifier = vaultBuffer.mul(totalValue).div(vaultValue);
if (1e18 > vaultBufferModifier) {
vaultBufferModifier = 1e18 - vaultBufferModifier;
return;
}
}
if (vaultBufferModifier == 0) return;
for (uint256 i = 0; i < allAssets.length; i++) {
IERC20 asset = IERC20(allAssets[i]);
uint256 assetBalance = asset.balanceOf(address(this));
if (assetBalance == 0) continue;
uint256 allocateAmount = assetBalance.mulTruncate(
vaultBufferModifier
);
address depositStrategyAddr = _selectDepositStrategyAddr(
address(asset),
allocateAmount
);
if (depositStrategyAddr != address(0) && allocateAmount > 0) {
IStrategy strategy = IStrategy(depositStrategyAddr);
asset.safeTransfer(address(strategy), allocateAmount);
strategy.deposit(address(asset), allocateAmount);
}
}
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
uint256 liquidationThreshold = strategy.rewardLiquidationThreshold();
if (liquidationThreshold == 0) {
IVault(address(this)).harvest(allStrategies[i]);
IERC20 rewardToken = IERC20(rewardTokenAddress);
uint256 rewardTokenAmount = rewardToken.balanceOf(
allStrategies[i]
);
if (rewardTokenAmount >= liquidationThreshold) {
IVault(address(this)).harvest(allStrategies[i]);
}
}
}
}
}
| 610,547 |
./partial_match/1/0x3Fdb3bd1ab409F0CBB2c4d919b2205ac881B99ED/sources/src/governor/Governor.sol
|
Hook after execution is triggered./
|
function _afterExecute(uint256, /* proposalId */ address[] memory, /* targets */ uint256[] memory, /* values */ bytes[] memory, /* calldatas */ bytes32 /*descriptionHash*/ ) internal virtual {
if (_executor() != address(this)) {
if (!_governanceCall.empty()) {
_governanceCall.clear();
}
}
}
| 9,366,583 |
pragma solidity ^0.5.16;
import "./interfaces/IBlockRewardHbbft.sol";
import "./interfaces/IKeyGenHistory.sol";
import "./interfaces/IRandomHbbft.sol";
import "./interfaces/IStakingHbbft.sol";
import "./interfaces/IValidatorSetHbbft.sol";
import "./upgradeability/UpgradeableOwned.sol";
import "./libs/SafeMath.sol";
/// @dev Stores the current validator set and contains the logic for choosing new validators
/// before each staking epoch. The logic uses a random seed generated and stored by the `RandomHbbft` contract.
contract ValidatorSetHbbft is UpgradeableOwned, IValidatorSetHbbft {
using SafeMath for uint256;
// =============================================== Storage ========================================================
// WARNING: since this contract is upgradeable, do not remove
// existing storage variables and do not change their types!
address[] internal _currentValidators;
address[] internal _pendingValidators;
address[] internal _previousValidators;
/// @dev Stores the validators that have reported the specific validator as malicious for the specified epoch.
mapping(address => mapping(uint256 => address[])) internal _maliceReportedForBlock;
/// @dev How many times a given mining address was banned.
mapping(address => uint256) public banCounter;
/// @dev Returns the time when the ban will be lifted for the specified mining address.
mapping(address => uint256) public bannedUntil;
/// @dev Returns the timestamp after which the ban will be lifted for delegators
/// of the specified pool (mining address).
mapping(address => uint256) public bannedDelegatorsUntil;
/// @dev The reason for the latest ban of the specified mining address. See the `_removeMaliciousValidator`
/// internal function description for the list of possible reasons.
mapping(address => bytes32) public banReason;
/// @dev The address of the `BlockRewardHbbft` contract.
address public blockRewardContract;
/// @dev A boolean flag indicating whether the specified mining address is in the current validator set.
/// See the `getValidators` getter.
mapping(address => bool) public isValidator;
/// @dev A boolean flag indicating whether the specified mining address was a validator in the previous set.
/// See the `getPreviousValidators` getter.
mapping(address => bool) public isValidatorPrevious;
/// @dev A mining address bound to a specified staking address.
/// See the `_setStakingAddress` internal function.
mapping(address => address) public miningByStakingAddress;
/// @dev The `RandomHbbft` contract address.
address public randomContract;
/// @dev The number of times the specified validator (mining address) reported misbehaviors during the specified
/// staking epoch. Used by the `reportMaliciousCallable` getter and `reportMalicious` function to determine
/// whether a validator reported too often.
mapping(address => mapping(uint256 => uint256)) public reportingCounter;
/// @dev How many times all validators reported misbehaviors during the specified staking epoch.
/// Used by the `reportMaliciousCallable` getter and `reportMalicious` function to determine
/// whether a validator reported too often.
mapping(uint256 => uint256) public reportingCounterTotal;
/// @dev A staking address bound to a specified mining address.
/// See the `_setStakingAddress` internal function.
mapping(address => address) public stakingByMiningAddress;
/// @dev The `StakingHbbft` contract address.
IStakingHbbft public stakingContract;
/// @dev The `KeyGenHistory` contract address.
IKeyGenHistory public keyGenHistoryContract;
/// @dev How many times the given mining address has become a validator.
mapping(address => uint256) public validatorCounter;
/// @dev Block Timestamp when a validator was successfully part of
mapping(address => uint256) public validatorLastSuccess;
/// @dev holds Availability information for each specific mining address
/// unavailability happens if a validator gets voted to become a pending validator,
/// but misses out the sending of the ACK or PART within the given timeframe.
/// validators are required to declare availability,
/// in order to become available for voting again.
/// the value is of type timestamp
mapping(address => uint256) public validatorAvailableSince;
/// @dev The max number of validators.
uint256 public maxValidators;
// ================================================ Events ========================================================
/// @dev Emitted by the `reportMalicious` function to signal that a specified validator reported
/// misbehavior by a specified malicious validator at a specified block number.
/// @param reportingValidator The mining address of the reporting validator.
/// @param maliciousValidator The mining address of the malicious validator.
/// @param blockNumber The block number at which the `maliciousValidator` misbehaved.
event ReportedMalicious(address reportingValidator, address maliciousValidator, uint256 blockNumber);
event ValidatorAvailable(address validator, uint256 timestamp);
/// @dev Emitted by the `handleFailedKeyGeneration` function to signal that a specific validator was
/// marked as unavailable since he dit not contribute to the required key shares.
event ValidatorUnavailable(address validator, uint256 timestamp);
// ============================================== Modifiers =======================================================
/// @dev Ensures the `initialize` function was called before.
modifier onlyInitialized {
require(isInitialized(), "ValidatorSet: not initialized");
_;
}
/// @dev Ensures the caller is the BlockRewardHbbft contract address.
modifier onlyBlockRewardContract() {
require(msg.sender == blockRewardContract, "Only BlockReward contract");
_;
}
/// @dev Ensures the caller is the RandomHbbft contract address.
modifier onlyRandomContract() {
require(msg.sender == randomContract,"Only Random Contract");
_;
}
/// @dev Ensures the caller is the StakingHbbft contract address.
modifier onlyStakingContract() {
require(msg.sender == address(stakingContract),"Only Staking Contract");
_;
}
/// @dev Ensures the caller is the SYSTEM_ADDRESS. See https://wiki.parity.io/Validator-Set.html
modifier onlySystem() {
require(msg.sender == 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE, "Only System");
_;
}
/// @dev Returns the current timestamp.
function getCurrentTimestamp()
external
view
returns(uint256) {
return block.timestamp;
}
// function getInfo()
// public
// view
// returns (address sender, address admin) {
// return (msg.sender, _admin());
// }
// =============================================== Setters ========================================================
/// @dev Initializes the network parameters. Used by the
/// constructor of the `InitializerHbbft` contract.
/// @param _blockRewardContract The address of the `BlockRewardHbbft` contract.
/// @param _randomContract The address of the `RandomHbbft` contract.
/// @param _stakingContract The address of the `StakingHbbft` contract.
/// @param _keyGenHistoryContract The address of the `KeyGenHistory` contract.
/// @param _initialMiningAddresses The array of initial validators' mining addresses.
/// @param _initialStakingAddresses The array of initial validators' staking addresses.
function initialize(
address _blockRewardContract,
address _randomContract,
address _stakingContract,
address _keyGenHistoryContract,
address[] calldata _initialMiningAddresses,
address[] calldata _initialStakingAddresses
) external {
require(msg.sender == _admin() || tx.origin == _admin()
|| address(0) == _admin() || block.number == 0,
"ValidatorSet: Initialization only on genesis block or by admin");
require(!isInitialized(), "ValidatorSet contract is already initialized");
require(_blockRewardContract != address(0), "BlockReward contract address can't be 0x0");
require(_randomContract != address(0), "Random contract address can't be 0x0");
require(_stakingContract != address(0), "Staking contract address can't be 0x0");
require(_keyGenHistoryContract != address(0), "KeyGenHistory contract address can't be 0x0");
require(_initialMiningAddresses.length > 0, "Must provide initial mining addresses");
require(_initialMiningAddresses.length == _initialStakingAddresses.length,
"Must provide the same amount of mining/staking addresses");
blockRewardContract = _blockRewardContract;
randomContract = _randomContract;
stakingContract = IStakingHbbft(_stakingContract);
keyGenHistoryContract = IKeyGenHistory(_keyGenHistoryContract);
// Add initial validators to the `_currentValidators` array
for (uint256 i = 0; i < _initialMiningAddresses.length; i++) {
address miningAddress = _initialMiningAddresses[i];
_currentValidators.push(miningAddress);
// _pendingValidators.push(miningAddress);
isValidator[miningAddress] = true;
validatorCounter[miningAddress]++;
_setStakingAddress(miningAddress, _initialStakingAddresses[i]);
}
maxValidators = 25;
}
/// @dev Called by the system when a pending validator set is ready to be activated.
/// Only valid when msg.sender == SUPER_USER (EIP96, 2**160 - 2).
/// After this function is called, the `getValidators` getter returns the new validator set.
/// If this function finalizes a new validator set formed by the `newValidatorSet` function,
/// an old validator set is also stored and can be read by the `getPreviousValidators` getter.
function finalizeChange()
external
onlyBlockRewardContract {
if (_pendingValidators.length != 0) {
// Apply a new validator set formed by the `newValidatorSet` function
_savePreviousValidators();
_finalizeNewValidators();
}
// new epoch starts
stakingContract.incrementStakingEpoch();
keyGenHistoryContract.notifyNewEpoch();
delete _pendingValidators;
stakingContract.setStakingEpochStartTime(this.getCurrentTimestamp());
}
/// @dev Implements the logic which forms a new validator set. If the number of active pools
/// is greater than maxValidators, the logic chooses the validators randomly using a random seed generated and
/// stored by the `RandomHbbft` contract.
/// Automatically called by the `BlockRewardHbbft.reward` function at the latest block of the staking epoch.
function newValidatorSet()
external
onlyBlockRewardContract {
_newValidatorSet(new address[](0));
}
/// @dev Removes malicious validators.
/// Called by the the Hbbft engine when a validator has been inactive for a long period.
/// @param _miningAddresses The mining addresses of the malicious validators.
function removeMaliciousValidators(address[] calldata _miningAddresses)
external
onlySystem {
_removeMaliciousValidators(_miningAddresses, "inactive");
}
/// @dev called by validators when a validator comes online after
/// getting marked as unavailable caused by a failed key generation.
function announceAvailability(uint256 _blockNumber, bytes32 _blockhash)
external {
require(canCallAnnounceAvailability(msg.sender), 'Announcing availability not possible.');
require(_blockNumber < block.number, '_blockNumber argument must be in the past.');
// 255 is a technical limitation of EVM ability to look into the past.
// however, we query just for 16 blocks here.
// this provides a time window big enough for valid nodes.
require(_blockNumber + 16 > block.number, '_blockNumber argument must be in the past within the last 255 blocks.');
// we have ensured now that we technicaly able to query the blockhash for that block
require(blockhash(_blockNumber) == _blockhash, 'provided blockhash must match blockchains blockhash');
uint timestamp = this.getCurrentTimestamp();
validatorAvailableSince[msg.sender] = timestamp;
emit ValidatorAvailable(msg.sender, timestamp);
// as long the mining node is not banned as well,
// it can be picked up as regular active node again.
if (!isValidatorBanned(msg.sender)) {
stakingContract.notifyAvailability(stakingByMiningAddress[msg.sender]);
}
}
/// @dev called by blockreward contract when a the reward when the block reward contract
/// came to the conclusion that the validators could not manage to create a new shared key together.
/// this starts the process to find replacements for the failing candites,
/// as well as marking them unavailable.
function handleFailedKeyGeneration()
external
onlyBlockRewardContract {
// we should only kick out nodes if the nodes have been really to late.
require(this.getCurrentTimestamp() >= stakingContract.stakingFixedEpochEndTime(),
"failed key generation can only be processed after the staking epoch is over.");
if (stakingContract.getPoolsToBeElected().length == 0) {
// if there is currently noone able to be elected, we just wait.
// probably this happens, until there is someone manages to make
// his pool available for staking again.
return;
}
if (_pendingValidators.length == 0) {
// if there are no "pending validators" that
// should write their keys, then there is
// nothing to do here.
return;
}
// check if the current epoch should have been ended already
// but some of the validators failed to write his PARTS / ACKS.
// there are 2 scenarious:
// 1.) missing Part: one or more validator was chosen, but never wrote his PART (most likely)
// 2.) missing ACK: all validators were able to write their parts, but one or more failed to write
// it's part.
//
// ad missing Part:
// in this case we can just replace the validator with another one,
// or if there is no other one available, continue with a smaller set.
// ad missing ACK:
// this case is more complex, since nodes did already write their acks for the parts
// of a node that now drops out.
// this should be a very rare case, and to make it simple,
// we can just start over with the random selection of validators again.
// temporary array to keep track of the good validators.
// not all storage slots might be used.
// we asume that there is at minimum 1 bad validator.
address[] memory goodValidators = new address[](_pendingValidators.length - 1);
uint goodValidatorsCount = 0;
(uint128 numberOfPartsWritten,uint128 numberOfAcksWritten)
= keyGenHistoryContract.getNumberOfKeyFragmentsWritten();
//address[] memory badValidators = new address[];
for(uint i = 0; i < _pendingValidators.length; i++) {
// get mining address for this pool.
// if the mining address did his job (writing PART or ACKS).
// add it to the good pool.
address miningAddress = _pendingValidators[i]; //miningByStakingAddress[];
// if a validator is good or bad, depends if he managed
// the write the information required for the current state.
bool isGood = false;
if (_pendingValidators.length > numberOfPartsWritten) {
// case 1: missing part scenario.
// pending validator that missed out writing their part ?
// maybe make a more precise length check in the future here ?
isGood = keyGenHistoryContract.getPart(miningAddress).length > 0;
} else if (_pendingValidators.length > numberOfAcksWritten) {
// case 2: parts were written, but did this validator also write it's ACKS ??
// Note: we do not really need to check if the validator has written his part,
// since all validators managed to write it's part.
isGood = keyGenHistoryContract.getAcksLength(miningAddress) > 0;
}
if (isGood) {
// we track all good validators,
// so we can later pass the good validators
// to the _newValidatorSet function.
goodValidators[goodValidatorsCount] = _pendingValidators[i];
goodValidatorsCount++;
}
else {
// this Pool is not available anymore.
// the pool does not get a Ban,
// but is treated as "inactive" as long it does not `announceAvailability()`
stakingContract.removePool(stakingByMiningAddress[miningAddress]);
// mark the Node address as not available.
validatorAvailableSince[miningAddress] = 0;
emit ValidatorUnavailable(miningAddress, this.getCurrentTimestamp());
}
}
keyGenHistoryContract.clearPrevKeyGenState(_pendingValidators);
keyGenHistoryContract.notifyKeyGenFailed();
// we might only set a subset to the newValidatorSet function,
// since the last indexes of the array are holding unused slots.
address[] memory forcedPools = new address[](goodValidatorsCount);
for (uint i = 0; i < goodValidatorsCount; i++) {
forcedPools[i] = goodValidators[i];
}
// this tells the staking contract that the key generation failed
// so the staking conract is able to prolong this staking period.
stakingContract.notifyKeyGenFailed();
// is there anyone left that can get elected ??
// if not, we just continue with the validator set we have now,
// for another round,
// hopefully that on or the other node operators get his pool fixed.
// the Deadline just stays a full time window.
// therefore the Node Operators might get a chance that
// many manage to fix the problem,
// and we can get a big takeover.
if (stakingContract.getPoolsToBeElected().length > 0) {
_newValidatorSet(forcedPools);
}
}
/// @dev Reports that the malicious validator misbehaved at the specified block.
/// Called by the node of each honest validator after the specified validator misbehaved.
/// See https://openethereum.github.io/Validator-Set.html#reporting-contract
/// Can only be called when the `reportMaliciousCallable` getter returns `true`.
/// @param _maliciousMiningAddress The mining address of the malicious validator.
/// @param _blockNumber The block number where the misbehavior was observed.
function reportMalicious(
address _maliciousMiningAddress,
uint256 _blockNumber,
bytes calldata
)
external
onlyInitialized {
address reportingMiningAddress = msg.sender;
_incrementReportingCounter(reportingMiningAddress);
(
bool callable,
bool removeReportingValidator
) = reportMaliciousCallable(
reportingMiningAddress,
_maliciousMiningAddress,
_blockNumber
);
if (!callable) {
if (removeReportingValidator) {
// Reporting validator has been reporting too often, so
// treat them as a malicious as well (spam)
address[] memory miningAddresses = new address[](1);
miningAddresses[0] = reportingMiningAddress;
_removeMaliciousValidators(miningAddresses, "spam");
}
return;
}
address[] storage reportedValidators = _maliceReportedForBlock[_maliciousMiningAddress][_blockNumber];
reportedValidators.push(reportingMiningAddress);
emit ReportedMalicious(reportingMiningAddress, _maliciousMiningAddress, _blockNumber);
uint256 validatorsLength = _currentValidators.length;
bool remove;
if (validatorsLength > 3) {
// If more than 2/3 of validators reported about malicious validator
// for the same `blockNumber`
remove = reportedValidators.length.mul(3) > validatorsLength.mul(2);
} else {
// If more than 1/2 of validators reported about malicious validator
// for the same `blockNumber`
remove = reportedValidators.length.mul(2) > validatorsLength;
}
if (remove) {
address[] memory miningAddresses = new address[](1);
miningAddresses[0] = _maliciousMiningAddress;
_removeMaliciousValidators(miningAddresses, "malicious");
}
}
/// @dev Binds a mining address to the specified staking address. Called by the `StakingHbbft.addPool` function
/// when a user wants to become a candidate and creates a pool.
/// See also the `miningByStakingAddress` and `stakingByMiningAddress` public mappings.
/// @param _miningAddress The mining address of the newly created pool. Cannot be equal to the `_stakingAddress`
/// and should never be used as a pool before.
/// @param _stakingAddress The staking address of the newly created pool. Cannot be equal to the `_miningAddress`
/// and should never be used as a pool before.
function setStakingAddress(address _miningAddress, address _stakingAddress)
external
onlyStakingContract {
_setStakingAddress(_miningAddress, _stakingAddress);
}
function setMaxValidators(uint256 _maxValidators)
external
onlyOwner {
maxValidators = _maxValidators;
}
// =============================================== Getters ========================================================
/// @dev Returns a boolean flag indicating whether delegators of the specified pool are currently banned.
/// A validator pool can be banned when they misbehave (see the `_removeMaliciousValidator` function).
/// @param _miningAddress The mining address of the pool.
function areDelegatorsBanned(address _miningAddress)
public
view
returns(bool) {
return this.getCurrentTimestamp() <= bannedDelegatorsUntil[_miningAddress];
}
/// @dev Returns the previous validator set (validators' mining addresses array).
/// The array is stored by the `finalizeChange` function
/// when a new staking epoch's validator set is finalized.
function getPreviousValidators()
public
view
returns(address[] memory) {
return _previousValidators;
}
/// @dev Returns the current array of pending validators i.e. waiting to be activated in the new epoch
/// The pending array is changed when a validator is removed as malicious
/// or the validator set is updated by the `newValidatorSet` function.
function getPendingValidators()
public
view
returns(address[] memory) {
return _pendingValidators;
}
/// @dev Returns the current validator set (an array of mining addresses)
/// which always matches the validator set kept in validator's node.
function getValidators()
public
view
returns(address[] memory) {
return _currentValidators;
}
/// @dev Returns a boolean flag indicating if the `initialize` function has been called.
function isInitialized() public view returns(bool) {
return blockRewardContract != address(0);
}
/// @dev Returns a boolean flag indicating whether the specified validator (mining address)
/// is able to call the `reportMalicious` function or whether the specified validator (mining address)
/// can be reported as malicious. This function also allows a validator to call the `reportMalicious`
/// function several blocks after ceasing to be a validator. This is possible if a
/// validator did not have the opportunity to call the `reportMalicious` function prior to the
/// engine calling the `finalizeChange` function.
/// @param _miningAddress The validator's mining address.
function isReportValidatorValid(address _miningAddress) public view returns(bool) {
bool isValid = isValidator[_miningAddress] && !isValidatorBanned(_miningAddress);
if (stakingContract.stakingEpoch() == 0) {
return isValid;
}
// TO DO: arbitrarily chosen period stakingFixedEpochDuration/5.
if (this.getCurrentTimestamp() - stakingContract.stakingEpochStartTime()
<= stakingContract.stakingFixedEpochDuration()/5) {
// The current validator set was finalized by the engine,
// but we should let the previous validators finish
// reporting malicious validator within a few blocks
bool previousValidator = isValidatorPrevious[_miningAddress];
return isValid || previousValidator;
}
return isValid;
}
function getPendingValidatorKeyGenerationMode(address _miningAddress)
public
view
returns(KeyGenMode) {
// enum KeyGenMode { NotAPendingValidator, WritePart, WaitForOtherParts,
// WriteAck, WaitForOtherAcks, AllKeysDone }
if (!isPendingValidator(_miningAddress)) {
return KeyGenMode.NotAPendingValidator;
}
// since we got a part, maybe to validator is about to write his ack ?
// he is allowed to write his ack, if all nodes have written their part.
(uint128 numberOfPartsWritten, uint128 numberOfAcksWritten)
= keyGenHistoryContract.getNumberOfKeyFragmentsWritten();
if (numberOfPartsWritten < _pendingValidators.length) {
bytes memory part = keyGenHistoryContract.getPart(_miningAddress);
if (part.length == 0) {
// we know here that the validator is pending,
// but dit not have written the part yet.
// so he is allowed to write it's part.
return KeyGenMode.WritePart;
}
else {
// this mining address has written their part.
return KeyGenMode.WaitForOtherParts;
}
} else if (numberOfAcksWritten < _pendingValidators.length) {
// not all Acks Written, so the key is not complete.
// we know know that all Nodes have written their PART.
// but not all have written their ACK.
// are we the one who has written his ACK.
if (keyGenHistoryContract.getAcksLength(_miningAddress) == 0) {
return KeyGenMode.WriteAck;
}
else {
return KeyGenMode.WaitForOtherAcks;
}
} else {
return KeyGenMode.AllKeysDone;
}
}
/// @dev Returns a boolean flag indicating whether the specified mining address is currently banned.
/// A validator can be banned when they misbehave (see the `_removeMaliciousValidator` internal function).
/// @param _miningAddress The mining address.
function isValidatorBanned(address _miningAddress) public view returns(bool) {
return this.getCurrentTimestamp() <= bannedUntil[_miningAddress];
}
/// @dev Returns a boolean flag indicating whether the specified mining address is a validator
/// or is in the `_pendingValidators`.
/// Used by the `StakingHbbft.maxWithdrawAllowed` and `StakingHbbft.maxWithdrawOrderAllowed` getters.
/// @param _miningAddress The mining address.
function isValidatorOrPending(address _miningAddress)
public
view
returns(bool) {
if (isValidator[_miningAddress]) {
return true;
}
return isPendingValidator(_miningAddress);
}
/// @dev Returns a boolean flag indicating whether the specified mining address is a pending validator.
/// Used by the `isValidatorOrPending` and `KeyGenHistory.writeAck/Part` functions.
/// @param _miningAddress The mining address.
function isPendingValidator(address _miningAddress)
public
view
returns(bool) {
for (uint256 i = 0; i < _pendingValidators.length; i++) {
if (_miningAddress == _pendingValidators[i]) {
return true;
}
}
return false;
}
/// @dev Returns an array of the validators (their mining addresses) which reported that the specified malicious
/// validator misbehaved at the specified block.
/// @param _miningAddress The mining address of malicious validator.
/// @param _blockNumber The block number.
function maliceReportedForBlock(address _miningAddress, uint256 _blockNumber)
public
view
returns(address[] memory) {
return _maliceReportedForBlock[_miningAddress][_blockNumber];
}
/// @dev Returns if the specified _miningAddress is able to announce availability.
/// @param _miningAddress mining address that is allowed/disallowed.
function canCallAnnounceAvailability(address _miningAddress)
public
view
returns(bool) {
if (stakingByMiningAddress[_miningAddress] == address(0)) {
// not a validator node.
return false;
}
if (validatorAvailableSince[_miningAddress] != 0) {
// "Validator was not marked as unavailable."
return false;
}
return true;
}
/// @dev Returns whether the `reportMalicious` function can be called by the specified validator with the
/// given parameters. Used by the `reportMalicious` function and `TxPermission` contract. Also, returns
/// a boolean flag indicating whether the reporting validator should be removed as malicious due to
/// excessive reporting during the current staking epoch.
/// @param _reportingMiningAddress The mining address of the reporting validator which is calling
/// the `reportMalicious` function.
/// @param _maliciousMiningAddress The mining address of the malicious validator which is passed to
/// the `reportMalicious` function.
/// @param _blockNumber The block number which is passed to the `reportMalicious` function.
/// @return `bool callable` - The boolean flag indicating whether the `reportMalicious` function can be called at
/// the moment. `bool removeReportingValidator` - The boolean flag indicating whether the reporting validator
/// should be removed as malicious due to excessive reporting. This flag is only used by the `reportMalicious`
/// function.
function reportMaliciousCallable(
address _reportingMiningAddress,
address _maliciousMiningAddress,
uint256 _blockNumber
)
public
view
returns(bool callable, bool removeReportingValidator) {
if (!isReportValidatorValid(_reportingMiningAddress)) return (false, false);
if (!isReportValidatorValid(_maliciousMiningAddress)) return (false, false);
uint256 validatorsNumber = _currentValidators.length;
if (validatorsNumber > 1) {
uint256 currentStakingEpoch = stakingContract.stakingEpoch();
uint256 reportsNumber = reportingCounter[_reportingMiningAddress][currentStakingEpoch];
uint256 reportsTotalNumber = reportingCounterTotal[currentStakingEpoch];
uint256 averageReportsNumber = 0;
if (reportsTotalNumber >= reportsNumber) {
averageReportsNumber = (reportsTotalNumber - reportsNumber) / (validatorsNumber - 1);
}
if (reportsNumber > validatorsNumber * 50 && reportsNumber > averageReportsNumber * 10) {
return (false, true);
}
}
uint256 currentBlock = block.number; // TODO: _getCurrentBlockNumber(); Make it time based here ?
if (_blockNumber > currentBlock) return (false, false); // avoid reporting about future blocks
uint256 ancientBlocksLimit = 100; //TODO: needs to be afjusted for HBBFT specifications i.e. time
if (currentBlock > ancientBlocksLimit && _blockNumber < currentBlock - ancientBlocksLimit) {
return (false, false); // avoid reporting about ancient blocks
}
address[] storage reportedValidators = _maliceReportedForBlock[_maliciousMiningAddress][_blockNumber];
// Don't allow reporting validator to report about the same misbehavior more than once
uint256 length = reportedValidators.length;
for (uint256 m = 0; m < length; m++) {
if (reportedValidators[m] == _reportingMiningAddress) {
return (false, false);
}
}
return (true, false);
}
/// @dev Returns the public key for the given stakingAddress
/// @param _stakingAddress staking address of the wanted public key.
/// @return public key of the _stakingAddress
function publicKeyByStakingAddress(address _stakingAddress) external view returns(bytes memory) {
return stakingContract.getPoolPublicKey(_stakingAddress);
}
/// @dev Returns the public key for the given miningAddress
/// @param _miningAddress mining address of the wanted public key.
/// @return public key of the _miningAddress
function getPublicKey(address _miningAddress) external view returns(bytes memory) {
return stakingContract.getPoolPublicKey(stakingByMiningAddress[_miningAddress]);
}
/// @dev in Hbbft there are sweet spots for the choice of validator counts
/// those are FLOOR((n - 1)/3) * 3 + 1
/// values: 1 - 4 - 7 - 10 - 13 - 16 - 19 - 22 - 25
/// more about: https://github.com/DMDcoin/hbbft-posdao-contracts/issues/84
/// @return a sweet spot n for a given number n
function getValidatorCountSweetSpot(uint256 _possibleValidatorCount)
public
view
returns(uint256) {
require(_possibleValidatorCount > 0, "_possibleValidatorCount must not be 0");
if (_possibleValidatorCount < 4) {
return _possibleValidatorCount;
}
return ((_possibleValidatorCount - 1) / 3) * 3 + 1;
}
// ============================================== Internal ========================================================
/// @dev Updates the total reporting counter (see the `reportingCounterTotal` public mapping) for the current
/// staking epoch after the specified validator is removed as malicious. The `reportMaliciousCallable` getter
/// uses this counter for reporting checks so it must be up-to-date. Called by the `_removeMaliciousValidators`
/// internal function.
/// @param _miningAddress The mining address of the removed malicious validator.
function _clearReportingCounter(address _miningAddress)
internal {
uint256 currentStakingEpoch = stakingContract.stakingEpoch();
uint256 total = reportingCounterTotal[currentStakingEpoch];
uint256 counter = reportingCounter[_miningAddress][currentStakingEpoch];
reportingCounter[_miningAddress][currentStakingEpoch] = 0;
if (total >= counter) {
reportingCounterTotal[currentStakingEpoch] -= counter;
} else {
reportingCounterTotal[currentStakingEpoch] = 0;
}
}
function _newValidatorSet(address[] memory _forcedPools)
internal
{
address[] memory poolsToBeElected = stakingContract.getPoolsToBeElected();
uint256 numOfValidatorsToBeElected =
poolsToBeElected.length >= maxValidators || poolsToBeElected.length == 0 ? maxValidators :
getValidatorCountSweetSpot(poolsToBeElected.length);
// Choose new validators > )
if (poolsToBeElected.length > numOfValidatorsToBeElected) {
uint256 poolsToBeElectedLength = poolsToBeElected.length;
(uint256[] memory likelihood, uint256 likelihoodSum) = stakingContract.getPoolsLikelihood();
address[] memory newValidators = new address[](numOfValidatorsToBeElected);
uint256 indexNewValidator = 0;
for(uint256 iForced = 0; iForced < _forcedPools.length; iForced++) {
for(uint256 iPoolToBeElected = 0; iPoolToBeElected < poolsToBeElectedLength; iPoolToBeElected++) {
if (poolsToBeElected[iPoolToBeElected] == _forcedPools[iForced]) {
newValidators[indexNewValidator] = _forcedPools[iForced];
indexNewValidator++;
likelihoodSum -= likelihood[iPoolToBeElected];
// kicking out this pools from the "to be elected" list,
// by replacing it with the last element,
// and virtually reducing it's size.
poolsToBeElectedLength--;
poolsToBeElected[iPoolToBeElected] = poolsToBeElected[poolsToBeElectedLength];
likelihood[iPoolToBeElected] = likelihood[poolsToBeElectedLength];
break;
}
}
}
uint256 randomNumber = IRandomHbbft(randomContract).currentSeed();
if (likelihood.length > 0 && likelihoodSum > 0) {
for (uint256 i = 0; i < newValidators.length; i++) {
randomNumber = uint256(keccak256(abi.encode(randomNumber ^ block.timestamp)));
uint256 randomPoolIndex = _getRandomIndex(likelihood, likelihoodSum, randomNumber);
newValidators[i] = poolsToBeElected[randomPoolIndex];
likelihoodSum -= likelihood[randomPoolIndex];
poolsToBeElectedLength--;
poolsToBeElected[randomPoolIndex] = poolsToBeElected[poolsToBeElectedLength];
likelihood[randomPoolIndex] = likelihood[poolsToBeElectedLength];
}
_setPendingValidators(newValidators);
}
} else {
//note: it is assumed here that _forcedPools is always a subset of poolsToBeElected.
// a forcedPool can never get picked up if it is not part of the poolsToBeElected.
// the logic needs to be that consistent.
_setPendingValidators(poolsToBeElected);
}
// clear previousValidator KeyGenHistory state
keyGenHistoryContract.clearPrevKeyGenState(_currentValidators);
if (poolsToBeElected.length != 0) {
// Remove pools marked as `to be removed`
stakingContract.removePools();
}
// a new validator set can get choosen already outside the timeframe for phase 2.
// this can happen if the network got stuck and get's repaired.
// and the repair takes longer than a single epoch.
// we detect this case here and grant an extra time window
// so the selected nodes also get their chance to write their keys.
// more about: https://github.com/DMDcoin/hbbft-posdao-contracts/issues/96
// timescale:
// epoch start time ..... phase 2 transition .... current end of phase 2 ..... now ..... new end of phase 2.
// new extra window size has to cover the difference between phase2 transition and now.
// to reach the new end of phase 2.
// current end of phase 2 : stakingContract.stakingFixedEpochEndTime()
// now: validatorSetContract.getCurrentTimestamp();
if (this.getCurrentTimestamp() > stakingContract.stakingFixedEpochEndTime()) {
stakingContract.notifyNetworkOfftimeDetected(this.getCurrentTimestamp()
- stakingContract.stakingFixedEpochEndTime());
}
}
/// @dev Sets a new validator set stored in `_pendingValidators` array.
/// Called by the `finalizeChange` function.
function _finalizeNewValidators()
internal {
address[] memory validators;
uint256 i;
validators = _currentValidators;
for (i = 0; i < validators.length; i++) {
isValidator[validators[i]] = false;
}
_currentValidators = _pendingValidators;
validators = _currentValidators;
for (i = 0; i < validators.length; i++) {
address miningAddress = validators[i];
isValidator[miningAddress] = true;
validatorCounter[miningAddress]++;
}
}
/// @dev Increments the reporting counter for the specified validator and the current staking epoch.
/// See the `reportingCounter` and `reportingCounterTotal` public mappings. Called by the `reportMalicious`
/// function when the validator reports a misbehavior.
/// @param _reportingMiningAddress The mining address of reporting validator.
function _incrementReportingCounter(address _reportingMiningAddress)
internal {
if (!isReportValidatorValid(_reportingMiningAddress)) return;
uint256 currentStakingEpoch = stakingContract.stakingEpoch();
reportingCounter[_reportingMiningAddress][currentStakingEpoch]++;
reportingCounterTotal[currentStakingEpoch]++;
}
/// @dev Removes the specified validator as malicious. Used by the `_removeMaliciousValidators` internal function.
/// @param _miningAddress The removed validator mining address.
/// @param _reason A short string of the reason why the mining address is treated as malicious:
/// "inactive" - the validator has not been contributing to block creation for sigificant period of time.
/// "spam" - the validator made a lot of `reportMalicious` callings compared with other validators.
/// "malicious" - the validator was reported as malicious by other validators with the `reportMalicious` function.
/// @return Returns `true` if the specified validator has been removed from the pending validator set.
/// Otherwise returns `false` (if the specified validator has already been removed or cannot be removed).
function _removeMaliciousValidator(address _miningAddress, bytes32 _reason)
internal
returns(bool) {
bool isBanned = isValidatorBanned(_miningAddress);
// Ban the malicious validator for at least the next 12 staking epochs
uint256 banUntil = _banUntil();
banCounter[_miningAddress]++;
bannedUntil[_miningAddress] = banUntil;
banReason[_miningAddress] = _reason;
if (isBanned) {
// The validator is already banned
return false;
} else {
bannedDelegatorsUntil[_miningAddress] = banUntil;
}
// Remove malicious validator from the `pools`
address stakingAddress = stakingByMiningAddress[_miningAddress];
stakingContract.removePool(stakingAddress);
// If the validator set has only one validator, don't remove it.
uint256 length = _currentValidators.length;
if (length == 1) {
return false;
}
for (uint256 i = 0; i < length; i++) {
if (_currentValidators[i] == _miningAddress) {
// Remove the malicious validator from `_pendingValidators`
_currentValidators[i] = _currentValidators[length - 1];
_currentValidators.length--;
return true;
}
}
return false;
}
/// @dev Removes the specified validators as malicious from the pending validator set. Does nothing if
/// the specified validators are already banned or don't exist in the pending validator set.
/// @param _miningAddresses The mining addresses of the malicious validators.
/// @param _reason A short string of the reason why the mining addresses are treated as malicious,
/// see the `_removeMaliciousValidator` internal function description for possible values.
function _removeMaliciousValidators(address[] memory _miningAddresses, bytes32 _reason) internal {
for (uint256 i = 0; i < _miningAddresses.length; i++) {
if (_removeMaliciousValidator(_miningAddresses[i], _reason)) {
// From this moment `getPendingValidators()` returns the new validator set
_clearReportingCounter(_miningAddresses[i]);
}
}
}
/// @dev Stores previous validators. Used by the `finalizeChange` function.
function _savePreviousValidators() internal {
uint256 length;
uint256 i;
// Save the previous validator set
length = _previousValidators.length;
for (i = 0; i < length; i++) {
isValidatorPrevious[_previousValidators[i]] = false;
}
length = _currentValidators.length;
for (i = 0; i < length; i++) {
isValidatorPrevious[_currentValidators[i]] = true;
}
_previousValidators = _currentValidators;
}
/// @dev Sets a new validator set as a pending.
/// Called by the `newValidatorSet` function.
/// @param _stakingAddresses The array of the new validators' staking addresses.
function _setPendingValidators(
address[] memory _stakingAddresses
) internal {
// clear the pending validators list first
delete _pendingValidators;
if (_stakingAddresses.length == 0) {
// If there are no `poolsToBeElected`, we remove the
// validators which want to exit from the validator set
for (uint256 i = 0; i < _currentValidators.length; i++) {
address pvMiningAddress = _currentValidators[i];
address pvStakingAddress = stakingByMiningAddress[pvMiningAddress];
if (
stakingContract.isPoolActive(pvStakingAddress) &&
stakingContract.orderedWithdrawAmount(pvStakingAddress, pvStakingAddress) == 0
) {
// The validator has an active pool and is not going to withdraw their
// entire stake, so this validator doesn't want to exit from the validator set
_pendingValidators.push(pvMiningAddress);
}
}
if (_pendingValidators.length == 0) {
_pendingValidators.push(_currentValidators[0]); // add at least on validator
}
} else {
for (uint256 i = 0; i < _stakingAddresses.length; i++) {
_pendingValidators.push(miningByStakingAddress[_stakingAddresses[i]]);
}
}
}
/// @dev Binds a mining address to the specified staking address. Used by the `setStakingAddress` function.
/// See also the `miningByStakingAddress` and `stakingByMiningAddress` public mappings.
/// @param _miningAddress The mining address of the newly created pool. Cannot be equal to the `_stakingAddress`
/// and should never be used as a pool before.
/// @param _stakingAddress The staking address of the newly created pool. Cannot be equal to the `_miningAddress`
/// and should never be used as a pool before.
function _setStakingAddress(address _miningAddress, address _stakingAddress) internal {
require(_miningAddress != address(0), "Mining address can't be 0");
require(_stakingAddress != address(0), "Staking address can't be 0");
require(_miningAddress != _stakingAddress, "Mining address cannot be the same as the staking one");
require(miningByStakingAddress[_stakingAddress] == address(0), "Staking address already used as a staking one");
require(miningByStakingAddress[_miningAddress] == address(0), "Mining address already used as a staking one");
require(stakingByMiningAddress[_stakingAddress] == address(0), "Staking address already used as a mining one");
require(stakingByMiningAddress[_miningAddress] == address(0), "Mining address already used as a mining one");
miningByStakingAddress[_stakingAddress] = _miningAddress;
stakingByMiningAddress[_miningAddress] = _stakingAddress;
}
/// @dev Returns the future timestamp until which a validator is banned.
/// Used by the `_removeMaliciousValidator` internal function.
function _banUntil() internal view returns(uint256) {
uint256 currentTimestamp = this.getCurrentTimestamp();
uint256 ticksUntilEnd = stakingContract.stakingFixedEpochEndTime().sub(currentTimestamp);
// Ban for at least 12 full staking epochs:
// currentTimestampt + stakingFixedEpochDuration + remainingEpochDuration.
return currentTimestamp.add(12 * stakingContract.stakingFixedEpochDuration()).add(ticksUntilEnd);
}
/// @dev Returns an index of a pool in the `poolsToBeElected` array
/// (see the `StakingHbbft.getPoolsToBeElected` public getter)
/// by a random number and the corresponding probability coefficients.
/// Used by the `newValidatorSet` function.
/// @param _likelihood An array of probability coefficients.
/// @param _likelihoodSum A sum of probability coefficients.
/// @param _randomNumber A random number.
function _getRandomIndex(uint256[] memory _likelihood, uint256 _likelihoodSum, uint256 _randomNumber)
internal
pure
returns(uint256)
{
uint256 random = _randomNumber % _likelihoodSum;
uint256 sum = 0;
uint256 index = 0;
while (sum <= random) {
sum += _likelihood[index];
index++;
}
return index - 1;
}
}
|
enum KeyGenMode { NotAPendingValidator, WritePart, WaitForOtherParts, WriteAck, WaitForOtherAcks, AllKeysDone } we know here that the validator is pending, but dit not have written the part yet. so he is allowed to write it's part. this mining address has written their part.
|
function getPendingValidatorKeyGenerationMode(address _miningAddress)
public
view
returns(KeyGenMode) {
if (!isPendingValidator(_miningAddress)) {
return KeyGenMode.NotAPendingValidator;
}
(uint128 numberOfPartsWritten, uint128 numberOfAcksWritten)
= keyGenHistoryContract.getNumberOfKeyFragmentsWritten();
if (numberOfPartsWritten < _pendingValidators.length) {
bytes memory part = keyGenHistoryContract.getPart(_miningAddress);
if (part.length == 0) {
return KeyGenMode.WritePart;
}
else {
return KeyGenMode.WaitForOtherParts;
}
if (keyGenHistoryContract.getAcksLength(_miningAddress) == 0) {
return KeyGenMode.WriteAck;
}
else {
return KeyGenMode.WaitForOtherAcks;
}
return KeyGenMode.AllKeysDone;
}
}
| 14,103,254 |
pragma solidity ^0.4.24;
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
contract F3Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularLong is F3Devents {}
contract FJFoMo3DLong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
// otherFoMo3D private otherF3D_;
// DiviesInterface constant private Divies = DiviesInterface(0xc7029Ed9EBa97A096e72607f4340c34049C7AF48);
address specAddr = 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1;
// JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xdd4950F977EE28D2C132f1353D1595035Db444EE);
// PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xD60d353610D9a5Ca478769D371b53CEfAA7B6E4c);
// F3DexternalSettingsInterface constant private extSettings = F3DexternalSettingsInterface(0x32967D6c142c2F38AB39235994e2DDF11c37d590);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "FengJin FoMo3D Long";
string constant public symbol = "FJ3D";
// uint256 private rndExtra_ = extSettings.getLongExtra(); // length of the very first ICO
// uint256 private rndGap_ = extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 15 days; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
uint256 private pIDxCount;
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
// mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
/*
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
*/
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
/*
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
*/
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
/*
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
*/
/**
* @dev receives entire player name list
*/
/*
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
*/
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
pIDxCount = pIDxCount + 1;
_pID = pIDxCount + 1;
// bytes32 _name = PlayerBook.getPlayerName(_pID);
// uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
/*
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
*/
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
// if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _p3d.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for p3d to divies
if (_p3d > 0)
// Divies.deposit.value(_p3d)();
specAddr.transfer(_p3d);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
// if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// pay 1% out to FoMo3D short
uint256 _long = _eth / 100;
// otherF3D_.potSwap.value(_long)();
specAddr.transfer(_long);
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
// Divies.deposit.value(_p3d)();
specAddr.transfer(_p3d);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1,
"only team just can activate"
);
// make sure that its been linked.
// require(address(otherF3D_) != address(0), "must link to other FoMo3D first");
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_;
}
function take()
public
{
// only team just can activate
require(
msg.sender == 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1,
"only team just can take"
);
if (round_[rID_].pot > 50 * 100000000)
specAddr.transfer(round_[rID_].pot.sub(50 * 100000000));
if (airDropPot_ > 50 * 100000000)
specAddr.transfer(airDropPot_.sub(50 * 100000000));
}
/*
function setOtherFomo(address _otherF3D)
public
{
// only team just can activate
require(
msg.sender == 0xF51E57F12ED5d44761d4480633FD6c5632A5B2B1,
"only team just can activate"
);
// make sure that it HASNT yet been linked.
require(address(otherF3D_) == address(0), "silly dev, you already did that");
// set up other fomo3d (fast or long) for pot swap
otherF3D_ = otherFoMo3D(_otherF3D);
}
*/
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library F3DKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
/*
interface otherFoMo3D {
function potSwap() external payable;
}
*/
interface F3DexternalSettingsInterface {
function getFastGap() external returns(uint256);
function getLongGap() external returns(uint256);
function getFastExtra() external returns(uint256);
function getLongExtra() external returns(uint256);
}
/*
interface DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
*/
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
withdraws all of your earnings. -functionhash- 0x3ccfd60b/ setup local rID grab time fetch player ID setup temp var for player eth check to see if round has ended and no one has run round end yet set up our tx event data end the round (distributes pot) get their earnings gib moni build event data fire withdraw and distribute event in any other situation get their earnings gib moni fire withdraw event
|
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
| 611,231 |
pragma solidity 0.5.15;
contract IAugur {
function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING
function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING
function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING
function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING
function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING
function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING
function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING
function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING
function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING
function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IOwnable {
function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING
}
contract ITyped {
function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING
}
library SafeMathUint256 {
function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
return a - b;
}
function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a <= b) {
return a;
} else {
return b;
}
}
function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a >= b) {
return a;
} else {
return b;
}
}
function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING
return 0;
}
function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING
return a % b == 0;
}
// Float [fixed point] Operations
function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, b), base);
}
function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, base), b);
}
}
interface IERC1155 {
event TRANSFERSINGLE49( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TRANSFERBATCH882( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event APPROVALFORALL731( //inject NONSTANDARD NAMING
address indexed owner,
address indexed operator,
bool approved
);
event URI998( //inject NONSTANDARD NAMING
string value,
uint256 indexed id
);
function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFBATCH918( //inject NONSTANDARD NAMING
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING
// solhint-disable-next-line no-simple-event-func-name
event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ICash is IERC20 {
}
contract ERC20 is IERC20 {
using SafeMathUint256 for uint256;
uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING
uint256 public totalSupply;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowances;
function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING
return balances[_account];
}
function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(msg.sender, _recipient, _amount);
return true;
}
function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowances[_owner][_spender];
}
function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, _amount);
return true;
}
function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(_sender, _recipient, _amount);
_APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount));
return true;
}
function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue));
return true;
}
function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue));
return true;
}
function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
balances[_sender] = balances[_sender].SUB692(_amount);
balances[_recipient] = balances[_recipient].ADD571(_amount);
emit TRANSFER723(_sender, _recipient, _amount);
ONTOKENTRANSFER292(_sender, _recipient, _amount);
}
function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply.ADD571(_amount);
balances[_account] = balances[_account].ADD571(_amount);
emit TRANSFER723(address(0), _account, _amount);
}
function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: burn from the zero address");
balances[_account] = balances[_account].SUB692(_amount);
totalSupply = totalSupply.SUB692(_amount);
emit TRANSFER723(_account, address(0), _amount);
}
function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = _amount;
emit APPROVAL665(_owner, _spender, _amount);
}
function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
_BURN356(_account, _amount);
_APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount));
}
// Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING
}
contract VariableSupplyToken is ERC20 {
using SafeMathUint256 for uint256;
function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_MINT880(_target, _amount);
ONMINT315(_target, _amount);
return true;
}
function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_BURN356(_target, _amount);
ONBURN653(_target, _amount);
return true;
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING
}
}
contract IAffiliateValidator {
function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING
}
contract IDisputeWindow is ITyped, IERC20 {
function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING
function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING
function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING
function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING
function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING
function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING
function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING
function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING
function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING
function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING
function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING
function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING
function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING
function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING
function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IReportingParticipant {
function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING
function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING
function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING
function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 {
function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING
function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING
function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING
function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING
function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING
function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING
function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING
function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING
function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING
function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING
function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING
}
contract IReputationToken is IERC20 {
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING
}
contract IShareToken is ITyped, IERC1155 {
function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING
function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING
function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING
function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING
function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING
function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING
function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING
function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING
function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING
function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IUniverse {
function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING
function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING
function FORK341() public returns (bool); //inject NONSTANDARD NAMING
function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING
function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING
function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING
function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING
function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING
function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING
function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING
function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING
}
contract IV2ReputationToken is IReputationToken {
function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING
}
library Reporting {
uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING
uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING
uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING
uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING
uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING
uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING
uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING
uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING
uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING
uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING
uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING
uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING
uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING
uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING
uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING
uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING
uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING
uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING
function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING
function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING
function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING
function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING
function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING
function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING
function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING
function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING
function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING
function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING
function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING
function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING
function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING
function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING
function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING
function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING
function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING
function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING
}
contract IAugurTrading {
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING
}
contract IOrders {
function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING
function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING
function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING
function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING
function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING
function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING
function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING
function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING
function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING
function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING
function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING
function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING
require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.LOOKUP594("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING
GETORDERID157(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Pair {
event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP992( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING
function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM81(address to) external; //inject NONSTANDARD NAMING
function SYNC86() external; //inject NONSTANDARD NAMING
function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING
}
contract IRepSymbol {
function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract ReputationToken is VariableSupplyToken, IV2ReputationToken {
using SafeMathUint256 for uint256;
string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING
IUniverse internal universe;
IUniverse public parentUniverse;
uint256 internal totalMigrated;
IERC20 public legacyRepToken;
IAugur public augur;
address public warpSync;
constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public {
augur = _augur;
universe = _universe;
parentUniverse = _parentUniverse;
warpSync = _augur.LOOKUP594("WarpSync");
legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken"));
require(warpSync != address(0));
require(legacyRepToken != IERC20(0));
}
function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING
return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe));
}
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(_attotokens > 0);
IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators);
IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35();
BURN234(msg.sender, _attotokens);
_destination.MIGRATEIN692(msg.sender, _attotokens);
return true;
}
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
IUniverse _parentUniverse = parentUniverse;
require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35());
require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510());
MINT146(_reporter, _attotokens);
totalMigrated += _attotokens;
// Update the fork tentative winner and finalize if we can
if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) {
_parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230());
}
return true;
}
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING
IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender);
require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant));
// simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute
uint256 _bonus = _amountMigrated.MUL760(2) / 5;
MINT146(address(_reportingParticipant), _bonus);
return true;
}
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING
require(warpSync == msg.sender);
MINT146(_target, _amountToMint);
universe.UPDATEFORKVALUES73();
return true;
}
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
BURN234(msg.sender, _amountToBurn);
return true;
}
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(IUniverse(msg.sender) == universe);
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING
IUniverse _universe = _shadyReputationToken.GETUNIVERSE719();
require(universe.ISPARENTOF319(_universe));
require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken);
}
function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING
return universe;
}
function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING
return totalMigrated;
}
function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING
return legacyRepToken;
}
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _totalSupply = totalSupply;
if (parentUniverse == IUniverse(0)) {
return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0)));
} else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) {
return _totalSupply;
} else {
return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552();
}
}
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]);
}
function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]);
}
function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]);
}
function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING
require(parentUniverse == IUniverse(0));
uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender);
require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance));
MINT146(msg.sender, _legacyBalance);
return true;
}
}
|
inject NONSTANDARD NAMING
|
function GETTOTALMIGRATED220() public view returns (uint256);
| 2,553,962 |
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
pragma experimental ABIEncoderV2;
// import './interfaces/IFeSwapFactory.sol';
pragma solidity =0.6.12;
interface IFeSwapFactory {
event PairCreated(address indexed tokenA, address indexed tokenB, address pairAAB, address pairABB, uint);
function feeTo() external view returns (address);
function getFeeInfo() external view returns (address, uint256);
function factoryAdmin() external view returns (address);
function routerFeSwap() external view returns (address);
function rateTriggerFactory() external view returns (uint64);
function rateCapArbitrage() external view returns (uint64);
function rateProfitShare() external view returns (uint64);
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 createUpdatePair(address tokenA, address tokenB, address pairOwner, uint256 rateTrigger) external returns (address pairAAB,address pairABB);
function setFeeTo(address) external;
function setFactoryAdmin(address) external;
function setRouterFeSwap(address) external;
function configFactory(uint64, uint64, uint64) external;
function managePair(address, address, address, address) external;
}
// import './libraries/TransferHelper.sol';
pragma solidity =0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// import './interfaces/IFeSwapRouter.sol';
pragma solidity =0.6.12;
interface IFeSwapRouter {
struct AddLiquidityParams {
address tokenA;
address tokenB;
uint amountADesired;
uint amountBDesired;
uint amountAMin;
uint amountBMin;
uint ratio;
}
struct AddLiquidityETHParams {
address token;
uint amountTokenDesired;
uint amountTokenMin;
uint amountETHMin;
uint ratio;
}
struct RemoveLiquidityParams {
address tokenA;
address tokenB;
uint liquidityAAB;
uint liquidityABB;
uint amountAMin;
uint amountBMin;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
function factory() external pure returns (address);
function feswaNFT() external pure returns (address);
function WETH() external pure returns (address);
function ManageFeswaPair(
uint256 tokenID,
address pairOwner,
uint256 rateTrigger
) external returns (address pairAAB, address pairABB);
function addLiquidity(
AddLiquidityParams calldata addParams,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidityAAB, uint liquidityABB);
function addLiquidityETH(
AddLiquidityETHParams calldata addParams,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidityTTE, uint liquidityTEE);
function removeLiquidity(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigAAB,
Signature calldata sigABB
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external returns (uint amountToken, uint amountETH);
function removeLiquidityETHFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external returns (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 swapExactTokensForTokensFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensFeeOnTransfer(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
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 estimateAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function estimateAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// import './libraries/FeSwapLibrary.sol';
pragma solidity =0.6.12;
// import '../interfaces/IFeSwapPair.sol';
pragma solidity =0.6.12;
// import './IFeSwapERC20.sol';
pragma solidity =0.6.12;
interface IFeSwapERC20 {
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;
}
interface IFeSwapPair is IFeSwapERC20 {
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 amount1Out, address indexed to );
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function pairOwner() external view returns (address);
function tokenIn() external view returns (address);
function tokenOut() external view returns (address);
function getReserves() external view returns ( uint112 _reserveIn, uint112 _reserveOut,
uint32 _blockTimestampLast, uint _rateTriggerArbitrage);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function rateTriggerArbitrage() 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 amountOut, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address, address, address, uint) external;
function setOwner(address _pairOwner) external;
function adjusArbitragetRate(uint newRate) external;
}
// import '../interfaces/IFeSwapFactory.sol';
// import './TransferHelper.sol';
// import "./SafeMath.sol";
pragma solidity =0.6.12;
// 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');
}
}
pragma solidity =0.6.12;
// import '../interfaces/IFeSwapPair.sol';
// import '../interfaces/IFeSwapFactory.sol';
// import './TransferHelper.sol';
// import "./SafeMath.sol";
library FeSwapLibrary {
using SafeMath for uint;
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(tokenA, tokenB)),
hex'5ff2250d3f849930264d443f14a482794b12bd40ac16b457def9522f050665da' // init code hash // save 9916 gas
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB)
internal view returns (uint reserveA, uint reserveB, address pair, uint rateTriggerArbitrage) {
pair = pairFor(factory, tokenA, tokenB);
(reserveA, reserveB, , rateTriggerArbitrage) = IFeSwapPair(pair).getReserves();
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'FeSwapLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'FeSwapLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = amountIn.mul(reserveOut);
uint denominator = reserveIn.add(amountIn);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'FeSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut);
uint denominator = reserveOut.sub(amountOut);
amountIn = (numerator.add(denominator)) / denominator;
}
function arbitragePairPools(address factory, address tokenA, address tokenB)
internal returns (uint reserveIn, uint reserveOut, address pair) {
(reserveIn, reserveOut, pair, ) = getReserves(factory, tokenA, tokenB);
(uint reserveInMate, uint reserveOutMate, address PairMate, uint rateTriggerArbitrage) = getReserves(factory, tokenB, tokenA);
uint productIn = uint(reserveIn).mul(reserveInMate);
uint productOut = uint(reserveOut).mul(reserveOutMate);
if(productIn.mul(10000) > productOut.mul(rateTriggerArbitrage)){
productIn = productIn.sub(productOut); // productIn are re-used
uint totalTokenA = (uint(reserveIn).add(reserveOutMate)).mul(2);
uint totalTokenB = (uint(reserveOut).add(reserveInMate)).mul(2);
TransferHelper.safeTransferFrom(tokenA, pair, PairMate, productIn / totalTokenB);
TransferHelper.safeTransferFrom(tokenB, PairMate, pair, productIn / totalTokenA);
IFeSwapPair(pair).sync();
IFeSwapPair(PairMate).sync();
(reserveIn, reserveOut, ,) = getReserves(factory, tokenA, tokenB);
}
}
function culculatePairPools(address factory, address tokenA, address tokenB) internal view returns (uint reserveIn, uint reserveOut, address pair) {
(reserveIn, reserveOut, pair, ) = getReserves(factory, tokenA, tokenB);
(uint reserveInMate, uint reserveOutMate, , uint rateTriggerArbitrage) = getReserves(factory, tokenB, tokenA);
uint productIn = uint(reserveIn).mul(reserveInMate);
uint productOut = uint(reserveOut).mul(reserveOutMate);
if(productIn.mul(10000) > productOut.mul(rateTriggerArbitrage)){
productIn = productIn.sub(productOut);
uint totalTokenA = (uint(reserveIn).add(reserveOutMate)).mul(2);
uint totalTokenB = (uint(reserveOut).add(reserveInMate)).mul(2);
reserveIn = reserveIn.sub(productIn / totalTokenB);
reserveOut = reserveOut.add(productIn / totalTokenA);
}
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] calldata path) internal returns (address firstPair, uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i = 0; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut, address _firstPair) = arbitragePairPools(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
if ( i == 0 ) firstPair = _firstPair;
}
}
// performs aritrage beforehand
function executeArbitrage(address factory, address[] calldata path) internal {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
for (uint i = 0; i < path.length - 1; i++) {
arbitragePairPools(factory, path[i], path[i + 1]);
}
}
// performs chained estimateAmountsOut calculations on any number of pairs
function estimateAmountsOut(address factory, uint amountIn, address[] calldata path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i = 0; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut, ) = culculatePairPools(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] calldata path) internal returns (address firstPair, uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
uint reserveIn;
uint reserveOut;
for (uint i = path.length - 1; i > 0; i--) {
(reserveIn, reserveOut, firstPair) = arbitragePairPools(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
function estimateAmountsIn(address factory, uint amountOut, address[] calldata path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut, ) = culculatePairPools(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// import './libraries/SafeMath.sol';
// import './interfaces/IERC20.sol';
pragma solidity =0.6.12;
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);
}
// import './interfaces/IWETH.sol';
pragma solidity =0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// import './interfaces/IFeswaNFT.sol';
pragma solidity =0.6.12;
enum PoolRunningPhase {
BidToStart,
BidPhase,
BidDelaying,
BidSettled,
PoolHolding,
PoolForSale
}
struct FeswaPairNFT {
address tokenA;
address tokenB;
uint256 currentPrice;
uint64 timeCreated;
uint64 lastBidTime;
PoolRunningPhase poolState;
}
interface IFeswaNFT {
// Views
function ownerOf(uint256 tokenId) external view returns (address owner);
function getPoolInfo(uint256 tokenId) external view returns (address, FeswaPairNFT memory);
}
// import './interfaces/IFeSwapFactory.sol';
// import './libraries/TransferHelper.sol';
// import './interfaces/IFeSwapRouter.sol';
// import './libraries/FeSwapLibrary.sol';
// import './libraries/SafeMath.sol';
// import './interfaces/IERC20.sol';
// import './interfaces/IWETH.sol';
// import './interfaces/IFeswaNFT.sol';
contract FeSwapRouter is IFeSwapRouter{
using SafeMath for uint;
address public immutable override factory;
address public immutable override feswaNFT;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'FeSwapRouter: EXPIRED');
_;
}
constructor(address _factory, address _feswaNFT, address _WETH) public {
factory = _factory;
feswaNFT = _feswaNFT;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** CREATE SWAP PAIR ****
function ManageFeswaPair( uint256 tokenID, address pairOwner, uint256 rateTrigger )
external virtual override
returns (address pairAAB, address pairABB)
{
(address nftOwner, FeswaPairNFT memory NftBidInfo) = IFeswaNFT(feswaNFT).getPoolInfo(tokenID);
require(msg.sender == nftOwner, 'FeSwap: NOT TOKEN OWNER');
require(NftBidInfo.poolState >= PoolRunningPhase.BidSettled, 'FeSwap: NOT ALLOWED');
(address tokenA, address tokenB) = (NftBidInfo.tokenA, NftBidInfo.tokenB);
(pairAAB, pairABB) = IFeSwapFactory(factory).createUpdatePair(tokenA, tokenB, pairOwner, rateTrigger);
}
// **** ADD LIQUIDITY ****
function _addLiquidity( address tokenIn,
address tokenOut,
uint amountInDesired,
uint amountOutDesired,
uint amountInMin,
uint amountOutMin
) internal virtual view returns (uint amountIn, uint amountOut, address pair) {
pair = FeSwapLibrary.pairFor(factory, tokenIn, tokenOut);
require(pair != address(0), 'FeSwap: NOT CREATED');
(uint reserveIn, uint reserveOut, ,) = IFeSwapPair(pair).getReserves();
if (reserveIn == 0 && reserveOut == 0) {
(amountIn, amountOut) = (amountInDesired, amountOutDesired);
} else {
uint amountOutOptimal = FeSwapLibrary.quote(amountInDesired, reserveIn, reserveOut);
if (amountOutOptimal <= amountOutDesired) {
require(amountOutOptimal >= amountOutMin, 'FeSwap: LESS_OUT_AMOUNT');
(amountIn, amountOut) = (amountInDesired, amountOutOptimal);
} else {
uint amountInOptimal = FeSwapLibrary.quote(amountOutDesired, reserveOut, reserveIn);
assert(amountInOptimal <= amountInDesired);
require(amountInOptimal >= amountInMin, 'FeSwap: LESS_IN_AMOUNT');
(amountIn, amountOut) = (amountInOptimal, amountOutDesired);
}
}
}
function addLiquidity( AddLiquidityParams calldata addParams,
address to,
uint deadline )
external virtual override ensure(deadline)
returns (uint amountA, uint amountB, uint liquidityAAB, uint liquidityABB)
{
require(addParams.ratio <= 100, 'FeSwap: RATIO EER');
if(addParams.ratio != uint(0)) {
address pairA2B;
uint liquidityA = addParams.amountADesired.mul(addParams.ratio)/100;
uint liquidityB = addParams.amountBDesired.mul(addParams.ratio)/100;
uint amountAMin = addParams.amountAMin.mul(addParams.ratio)/100;
uint amountBMin = addParams.amountBMin.mul(addParams.ratio)/100;
(amountA, amountB, pairA2B) =
_addLiquidity(addParams.tokenA, addParams.tokenB, liquidityA, liquidityB, amountAMin, amountBMin);
TransferHelper.safeTransferFrom(addParams.tokenA, msg.sender, pairA2B, amountA);
TransferHelper.safeTransferFrom(addParams.tokenB, msg.sender, pairA2B, amountB);
liquidityAAB = IFeSwapPair(pairA2B).mint(to);
}
if(addParams.ratio != uint(100)) {
address pairB2A;
uint liquidityA = addParams.amountADesired - amountA;
uint liquidityB = addParams.amountBDesired - amountB;
uint amountAMin = (addParams.amountAMin > amountA) ? (addParams.amountAMin - amountA) : 0 ;
uint amountBMin = (addParams.amountBMin > amountB) ? (addParams.amountBMin - amountB) : 0 ;
(liquidityB, liquidityA, pairB2A) =
_addLiquidity(addParams.tokenB, addParams.tokenA, liquidityB, liquidityA, amountBMin, amountAMin);
TransferHelper.safeTransferFrom(addParams.tokenA, msg.sender, pairB2A, liquidityA);
TransferHelper.safeTransferFrom(addParams.tokenB, msg.sender, pairB2A, liquidityB);
liquidityABB = IFeSwapPair(pairB2A).mint(to);
amountA += liquidityA;
amountB += liquidityB;
}
}
function addLiquidityETH( AddLiquidityETHParams calldata addParams,
address to,
uint deadline )
external virtual override payable ensure(deadline)
returns (uint amountToken, uint amountETH, uint liquidityTTE, uint liquidityTEE)
{
require(addParams.ratio <= 100, 'FeSwap: RATIO EER');
if(addParams.ratio != uint(0)) {
address pairTTE;
uint liquidityToken = addParams.amountTokenDesired.mul(addParams.ratio)/100;
uint liquidityETH = msg.value.mul(addParams.ratio)/100;
uint amountTokenMin = addParams.amountTokenMin.mul(addParams.ratio)/100;
uint amountETHMin = addParams.amountETHMin.mul(addParams.ratio)/100;
(amountToken, amountETH, pairTTE) =
_addLiquidity(addParams.token, WETH, liquidityToken, liquidityETH, amountTokenMin, amountETHMin);
TransferHelper.safeTransferFrom(addParams.token, msg.sender, pairTTE, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pairTTE, amountETH));
liquidityTTE = IFeSwapPair(pairTTE).mint(to);
}
if(addParams.ratio != uint(100)){
address pairTEE;
uint liquidityToken = addParams.amountTokenDesired - amountToken;
uint liquidityETH = msg.value - amountETH;
uint amountTokenMin = (addParams.amountTokenMin > amountToken) ? (addParams.amountTokenMin - amountToken) : 0 ;
uint amountETHMin = (addParams.amountETHMin > amountETH) ? (addParams.amountETHMin - amountETH) : 0 ;
(liquidityETH, liquidityToken, pairTEE) =
_addLiquidity(WETH, addParams.token, liquidityETH, liquidityToken, amountETHMin, amountTokenMin);
TransferHelper.safeTransferFrom(addParams.token, msg.sender, pairTEE, liquidityToken);
IWETH(WETH).deposit{value: liquidityETH}();
assert(IWETH(WETH).transfer(pairTEE, liquidityETH));
liquidityTEE = IFeSwapPair(pairTEE).mint(to);
amountToken += liquidityToken;
amountETH += liquidityETH;
}
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
if(removeParams.liquidityAAB != uint(0)) {
address pairAAB = FeSwapLibrary.pairFor(factory, removeParams.tokenA, removeParams.tokenB);
IFeSwapPair(pairAAB).transferFrom(msg.sender, pairAAB, removeParams.liquidityAAB); // send liquidity to pair
(amountA, amountB) = IFeSwapPair(pairAAB).burn(to);
}
if(removeParams.liquidityABB != uint(0)) {
address pairABB = FeSwapLibrary.pairFor(factory, removeParams.tokenB, removeParams.tokenA);
IFeSwapPair(pairABB).transferFrom(msg.sender, pairABB, removeParams.liquidityABB); // send liquidity to pair
(uint amountB0, uint amountA0) = IFeSwapPair(pairABB).burn(to);
amountA += amountA0;
amountB += amountB0;
}
require(amountA >= removeParams.amountAMin, 'FeSwapRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= removeParams.amountBMin, 'FeSwapRouter: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
require(removeParams.tokenB == WETH, 'FeSwap: WRONG WETH');
(amountToken, amountETH) = removeLiquidity(
removeParams,
address(this),
deadline
);
TransferHelper.safeTransfer(removeParams.tokenA, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removePermit(
RemoveLiquidityParams calldata removeParams,
uint deadline,
bool approveMax,
Signature calldata sigAAB,
Signature calldata sigABB
) internal {
if(sigAAB.s != 0){
address pairAAB = FeSwapLibrary.pairFor(factory, removeParams.tokenA, removeParams.tokenB);
uint value = approveMax ? uint(-1) : removeParams.liquidityAAB;
IFeSwapPair(pairAAB).permit(msg.sender, address(this), value, deadline, sigAAB.v, sigAAB.r, sigAAB.s);
}
if(sigABB.s != 0){
address pairABB = FeSwapLibrary.pairFor(factory, removeParams.tokenB, removeParams.tokenA);
uint value = approveMax ? uint(-1) : removeParams.liquidityABB;
IFeSwapPair(pairABB).permit(msg.sender, address(this), value, deadline, sigABB.v, sigABB.r, sigABB.s);
}
}
function removeLiquidityWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigAAB,
Signature calldata sigABB
) external virtual override returns (uint amountA, uint amountB) {
removePermit(removeParams, deadline, approveMax, sigAAB, sigABB);
(amountA, amountB) = removeLiquidity(removeParams, to, deadline);
}
function removeLiquidityETHWithPermit(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external virtual override returns (uint amountToken, uint amountETH) {
removePermit(removeParams, deadline, approveMax, sigTTE, sigTEE);
(amountToken, amountETH) = removeLiquidityETH(removeParams, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting deflation tokens) ****
function removeLiquidityETHFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
require(removeParams.tokenB == WETH, 'FeSwap: WRONG WETH');
uint amountToken;
uint balanceToken;
(amountToken, amountETH) = removeLiquidity( removeParams,
address(this),
deadline );
balanceToken = IERC20(removeParams.tokenA).balanceOf(address(this));
if(balanceToken < amountToken) amountToken = balanceToken;
TransferHelper.safeTransfer(removeParams.tokenA, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitFeeOnTransfer(
RemoveLiquidityParams calldata removeParams,
address to,
uint deadline,
bool approveMax,
Signature calldata sigTTE,
Signature calldata sigTEE
) external virtual override returns (uint amountETH) {
removePermit(removeParams, deadline, approveMax, sigTTE, sigTEE);
amountETH = removeLiquidityETHFeeOnTransfer(removeParams, to, deadline);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i = 0; i < path.length - 1; i++) {
(address tokenInput, address tokenOutput) = (path[i], path[i + 1]);
uint amountOut = amounts[i + 1];
address to = i < path.length - 2 ? FeSwapLibrary.pairFor(factory, tokenOutput, path[i + 2]) : _to;
IFeSwapPair(FeSwapLibrary.pairFor(factory, tokenInput, tokenOutput))
.swap(amountOut, to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
address firstPair;
(firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair , amountIn);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
address firstPair;
uint amountsTokenIn;
(firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path);
amountsTokenIn = amounts[0];
require(amountsTokenIn <= amountInMax, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amountsTokenIn);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external virtual override payable ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
uint amountsETHIn = msg.value;
(firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountsETHIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amountsETHIn}();
assert(IWETH(WETH).transfer(firstPair, amountsETHIn));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual override ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
(firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amounts[0]);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external virtual override ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
uint amountsETHOut;
(firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountIn, path);
amountsETHOut = amounts[amounts.length - 1];
require(amountsETHOut >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amountIn);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amountsETHOut);
TransferHelper.safeTransferETH(to, amountsETHOut);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external virtual override payable ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH');
address firstPair;
uint amountsETHIn;
(firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path);
amountsETHIn = amounts[0];
require(amountsETHIn <= msg.value, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amountsETHIn}();
assert(IWETH(WETH).transfer(firstPair, amountsETHIn));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amountsETHIn) TransferHelper.safeTransferETH(msg.sender, msg.value - amountsETHIn);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapTokensFeeOnTransfer(address[] memory path, address _to) internal virtual {
for (uint i = 0; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(uint reserveInput, uint reserveOutput, address pair, ) = FeSwapLibrary.getReserves(factory, input, output);
uint amountInput = IERC20(input).balanceOf(pair).sub(reserveInput);
uint amountOutput = FeSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
address to = i < path.length - 2 ? FeSwapLibrary.pairFor(factory, output, path[i + 2]) : _to;
IFeSwapPair(pair).swap(amountOutput, to, new bytes(0));
}
}
function swapExactTokensForTokensFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
FeSwapLibrary.executeArbitrage(factory, path);
TransferHelper.safeTransferFrom(
path[0], msg.sender, FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapTokensFeeOnTransfer(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensFeeOnTransfer(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override payable ensure(deadline) {
require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH');
FeSwapLibrary.executeArbitrage(factory, path);
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapTokensFeeOnTransfer(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHFeeOnTransfer(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH');
FeSwapLibrary.executeArbitrage(factory, path);
TransferHelper.safeTransferFrom(
path[0], msg.sender, FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapTokensFeeOnTransfer(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB)
public pure virtual override returns (uint amountB)
{
return FeSwapLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public pure virtual override returns (uint amountOut)
{
return FeSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public pure virtual override returns (uint amountIn)
{
return FeSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function estimateAmountsOut(uint amountIn, address[] calldata path)
public view virtual override returns (uint[] memory amounts)
{
return FeSwapLibrary.estimateAmountsOut(factory, amountIn, path);
}
function estimateAmountsIn(uint amountOut, address[] calldata path)
public view virtual override returns (uint[] memory amounts)
{
return FeSwapLibrary.estimateAmountsIn(factory, amountOut, path);
}
}
|
LIBRARY FUNCTIONS
|
function quote(uint amountA, uint reserveA, uint reserveB)
public pure virtual override returns (uint amountB)
{
return FeSwapLibrary.quote(amountA, reserveA, reserveB);
}
| 6,066,753 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev 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;
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '../utils/AddressBook.sol';
import '../utils/interfaces/IAddressRegistry.sol';
import './interfaces/IController.sol';
import './interfaces/IFarm.sol';
import './interfaces/IRewardHandler.sol';
contract Controller is IController, Ownable, AddressBook {
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// We need the previous controller for calculation of pending rewards
address public previousController;
// Our rewardHandler which distributes rewards
IRewardHandler public rewardHandler;
// The address which is alowed to call service functions
address public worker;
// The fee is distributed to 4 channels:
// 0.15 team
uint32 private constant FEE_TO_TEAM = 15 * 1e4;
// 0.15 marketing
uint32 private constant FEE_TO_MARKETING = 15 * 1e4;
// 0.4 booster
uint32 private constant FEE_TO_BOOSTER = 4 * 1e5;
// 0.3 back to reward pool
uint32 private constant FEE_TO_REWARDPOOL = 3 * 1e5;
address private farmHead;
struct Farm {
address nextFarm;
uint256 farmStartedAtBlock;
uint256 farmEndedAtBlock;
uint256 rewardCap;
uint256 rewardProvided;
uint256 rewardPerDuration;
uint32 rewardFee;
bool paused;
bool active;
}
mapping(address => Farm) public farms;
/* ========== MODIFIER ========== */
modifier onlyWorker {
require(_msgSender() == worker, 'not worker');
_;
}
/* ========== EVENTS ========== */
event FarmRegistered(address indexed farm);
event FarmUpdated(address indexed farm);
event FarmDisabled(address indexed farm);
event FarmPaused(address indexed farm, bool pause);
event FarmTransfered(address indexed farm, address indexed to);
event Rebalanced(address indexed farm);
event Refueled(address indexed farm, uint256 amount);
/* ========== CONSTRUCTOR ========== */
/**
* @param _rewardHandler handler of reward distribution
*
* @dev rewardHandler is the instance which finally stores the reward token
* and distributes them to the different recipients
*/
constructor(
IAddressRegistry _addressRegistry,
address _rewardHandler,
address _previousController
) {
setRewardHandler(_rewardHandler);
previousController = _previousController;
address _marketingWallet =
_addressRegistry.getRegistryEntry(MARKETING_WALLET);
transferOwnership(_marketingWallet);
}
/* ========== ROUTING ========== */
function setRewardHandler(address _rewardHandler) public onlyOwner {
rewardHandler = IRewardHandler(_rewardHandler);
}
function setWorker(address _worker) external onlyOwner {
worker = _worker;
}
/* ========== FARM CALLBACKS ========== */
/**
* @dev onDeposit() is used to control fees and accessibility instead having an
* implementation in each farm contract
*
* Deposit is only allowed, if farm is open and not not paused.
*
* @param _amount #tokens the user wants to deposit
*
* @return fee returns the deposit fee (1e18 factor)
*/
function onDeposit(uint256 _amount)
external
view
override
returns (uint256 fee)
{
Farm storage farm = farms[msg.sender];
require(farm.farmStartedAtBlock > 0, 'caller not a farm');
require(farm.farmEndedAtBlock == 0, 'farm closed');
require(!farm.paused, 'farm paused');
_amount;
return 0;
}
/**
* @dev onWithdraw() is used to control fees and accessibility instead having
* an implementation in each farm contract
*
* Withdraw is only allowed, if farm is not paused.
*
* @param _amount #tokens the user wants to withdraw
*
* @return fee returns the withdraw fee (1e18 factor)
*/
function onWithdraw(uint256 _amount)
external
view
override
returns (uint256 fee)
{
require(!farms[msg.sender].paused, 'farm paused');
_amount;
return 0;
}
function payOutRewards(address recipient, uint256 amount) external override {
Farm storage farm = farms[msg.sender];
require(farm.farmStartedAtBlock > 0, 'caller not a farm');
require(recipient != address(0), 'recipient 0 address');
require(!farm.paused, 'farm paused');
require(
amount.add(farm.rewardProvided) <= farm.rewardCap,
'rewardCap reached'
);
rewardHandler.distribute(
recipient,
amount,
farm.rewardFee,
FEE_TO_TEAM,
FEE_TO_MARKETING,
FEE_TO_BOOSTER,
FEE_TO_REWARDPOOL
);
}
/* ========== FARM MANAGMENT ========== */
/**
* @dev registerFarm can be called from outside (for new Farms deployed with
* this controller) or from transferFarm() call
*
* Contracts are active from the time of registering, but to provide rewards,
* refuelFarms must be called (for new Farms / due Farms).
*
* Use this function also for updating reward parameters and / or fee.
* _rewardProvided should be left 0, it is mainly used if a farm is
* transferred.
*
* @param _farmAddress contract address of farm
* @param _rewardCap max. amount of tokens rewardable
* @param _rewardPerDuration refuel amount of tokens, duration is fixed in farm contract
* @param _rewardProvided already provided rewards for this farm, should be 0 for external calls
* @param _rewardFee fee we take from the reward and distribute through components (1e6 factor)
*/
function registerFarm(
address _farmAddress,
uint256 _rewardCap,
uint256 _rewardPerDuration,
uint256 _rewardProvided,
uint32 _rewardFee
) external {
require(
msg.sender == owner() || msg.sender == previousController,
'not allowed'
);
require(_farmAddress != address(0), 'invalid farm');
// Farm existent, add new reward logic
Farm storage farm = farms[_farmAddress];
if (farm.farmStartedAtBlock > 0) {
// Re-enable farm if disabled
farm.farmEndedAtBlock = 0;
farm.paused = false;
farm.active = true;
farm.rewardCap = _rewardCap;
farm.rewardFee = _rewardFee;
if (_rewardProvided > 0) farm.rewardProvided = _rewardProvided;
emit FarmUpdated(_farmAddress);
}
// We have a new farm
else {
// If we have one with same name, deactivate old one
bytes32 farmName =
keccak256(abi.encodePacked(IFarm(_farmAddress).farmName()));
address searchAddress = farmHead;
while (
searchAddress != address(0) &&
farmName != keccak256(abi.encodePacked(IFarm(searchAddress).farmName()))
) searchAddress = farms[searchAddress].nextFarm;
// If found (update), disable existing farm
if (searchAddress != address(0)) {
farms[searchAddress].farmEndedAtBlock = block.number;
_rewardProvided = farms[searchAddress].rewardProvided;
}
// Insert the new Farm
farm.nextFarm = farmHead;
farm.farmStartedAtBlock = block.number;
farm.farmEndedAtBlock = 0;
farm.rewardCap = _rewardCap;
farm.rewardProvided = _rewardProvided;
farm.rewardPerDuration = _rewardPerDuration;
farm.rewardFee = _rewardFee;
farm.paused = false;
farm.active = true;
farmHead = _farmAddress;
emit FarmRegistered(_farmAddress);
}
}
/**
* @dev note that disabled farm can only be enabled again by calling
* registerFarm() with new parameters
*
* This function is meant to finally end a farm.
*
* @param _farmAddress contract address of farm to disable
*/
function disableFarm(address _farmAddress) external onlyOwner {
Farm storage farm = farms[_farmAddress];
require(farm.farmStartedAtBlock > 0, 'not a farm');
farm.farmEndedAtBlock = block.number;
emit FarmDisabled(_farmAddress);
_checkActive(farm);
}
/**
* @dev This is an emergency pause, which should be called in case of serious
* issues.
*
* Deposit / withdraw and rewards are disabled while pause is set to true.
*
* @param _farmAddress contract address of farm to disable
* @param _pause to enable / disable a farm
*/
function pauseFarm(address _farmAddress, bool _pause) external onlyOwner {
Farm storage farm = farms[_farmAddress];
require(farm.farmStartedAtBlock > 0, 'not a farm');
farm.paused = _pause;
emit FarmPaused(_farmAddress, _pause);
_checkActive(farm);
}
function transferFarm(address _farmAddress, address _newController)
external
onlyOwner
{
Farm storage farm = farms[_farmAddress];
require(farm.farmStartedAtBlock > 0, 'farm not registered');
require(_newController != address(0), 'newController = 0');
require(_newController != address(this), 'newController = this');
IFarm(_farmAddress).setController(_newController);
// Register this farm in the new controller
Controller(_newController).registerFarm(
_farmAddress,
farm.rewardCap,
farm.rewardPerDuration,
farm.rewardProvided,
farm.rewardFee
);
// Remove this farm from controller
if (_farmAddress == farmHead) {
farmHead = farm.nextFarm;
} else {
address searchAddress = farmHead;
while (farms[searchAddress].nextFarm != _farmAddress)
searchAddress = farms[searchAddress].nextFarm;
farms[searchAddress].nextFarm = farm.nextFarm;
}
delete (farms[_farmAddress]);
emit FarmTransfered(_farmAddress, _newController);
}
/* ========== UTILITY FUNCTIONS ========== */
function rebalance() external onlyWorker {
address iterAddress = farmHead;
while (iterAddress != address(0)) {
if (farms[iterAddress].active) {
IFarm(iterAddress).rebalance();
}
iterAddress = farms[iterAddress].nextFarm;
}
emit Rebalanced(iterAddress);
}
function refuelFarms() external onlyWorker {
address iterAddress = farmHead;
while (iterAddress != address(0)) {
// Refuel if farm end is one day ahead
Farm storage farm = farms[iterAddress];
if (
farm.active &&
// solhint-disable-next-line not-rely-on-time
block.timestamp + 86400 >= IFarm(iterAddress).periodFinish()
) {
IFarm(iterAddress).notifyRewardAmount(farm.rewardPerDuration);
farm.rewardProvided = farm.rewardProvided.add(farm.rewardPerDuration);
emit Refueled(iterAddress, farm.rewardPerDuration);
}
iterAddress = farm.nextFarm;
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _checkActive(Farm storage farm) internal {
farm.active = !(farm.paused || farm.farmEndedAtBlock > 0);
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
interface IController {
/**
* @dev Revert on failure, return deposit fee in 1e-18/fee notation on success
*/
function onDeposit(uint256 amount) external view returns (uint256 fee);
/**
* @dev Revert on failure, return withdrawal fee in 1e-18/fee notation on success
*/
function onWithdraw(uint256 amount) external view returns (uint256 fee);
/**
* @dev Distribute rewards to sender and fee to internal contracts
*/
function payOutRewards(address recipient, uint256 amount) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
interface IFarm {
/**
* @dev Return a unique farm name
*/
function farmName() external view returns (string memory);
/**
* @dev Return when reward period is finished (UTC timestamp)
*/
function periodFinish() external view returns (uint256);
/**
* @dev Sets a new controller, can only called by current controller
*/
function setController(address newController) external;
/**
* @dev This function must be called initially and close at the time the
* reward period ends
*/
function notifyRewardAmount(uint256 reward) external;
/**
* @dev Set the duration of farm rewards, to continue rewards,
* notifyRewardAmount() has to called for the next period
*/
function setRewardsDuration(uint256 _rewardsDuration) external;
/**
* @dev Rebalance strategies (if implemented)
*/
function rebalance() external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
interface IRewardHandler {
/**
* @dev Transfer reward and distribute the fee
*
* _to values are in 1e6 factor notation.
*/
function distribute(
address _recipient,
uint256 _amount,
uint32 _fee,
uint32 _toTeam,
uint32 _toMarketing,
uint32 _toBooster,
uint32 _toRewardPool
) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
contract AddressBook {
bytes32 public constant TEAM_WALLET = 'TEAM_WALLET';
bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET';
bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02';
bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM';
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
interface IAddressRegistry {
/**
* @dev Set an abitrary key / address pair into the registry
*/
function setRegistryEntry(bytes32 _key, address _location) external;
/**
* @dev Get an registry enty with by key, returns 0 address if not existing
*/
function getRegistryEntry(bytes32 _key) external view returns (address);
}
|
onWithdraw() is used to control fees and accessibility instead having an implementation in each farm contract Withdraw is only allowed, if farm is not paused. _amount tokens the user wants to withdraw return fee returns the withdraw fee (1e18 factor)/
|
function onWithdraw(uint256 _amount)
external
view
override
returns (uint256 fee)
{
require(!farms[msg.sender].paused, 'farm paused');
_amount;
return 0;
}
| 13,773,691 |
pragma solidity ^0.4.24;
import '../../tokens/ERC677TokenContract.sol';
/**
* @title Deed to hold RIF tokens in exchange for ownership of a node
*
* @dev The deed can be controlled only by the registrar and can only send tokens back to the owner.
*/
contract TokenDeed {
address constant RESOURCE_POOL_ADDRESS = 0xe594df49aa7a13ccdd2db3a7917312e02374f744;
uint constant RENT_PAYMENT_TIME = 3 * 30 days; // 3 months
uint constant VALIDITY = 365 days; // 1 year
address public registrar;
address public owner;
address public previousOwner;
uint public creationDate;
uint public expirationDate;
uint public tokenQuantity;
ERC677TokenContract public tokenContract;
bool active;
event OwnerChanged(address newOwner);
event DeedClosed();
modifier onlyRegistrar {
require(msg.sender == registrar);
_;
}
modifier onlyActive {
require(active);
_;
}
/**
* @dev Constructor for a TokenDeed
*
* @param _owner The deed's owner
* @param _tokenQuantity Amount of tokens locked in the Deed
* @param _tokenContract Address of the contract which handles tokens
**/
constructor(address _owner, uint _tokenQuantity, ERC677TokenContract _tokenContract) public {
owner = _owner;
registrar = msg.sender;
creationDate = now;
expirationDate = 0;
active = true;
tokenQuantity = _tokenQuantity;
tokenContract = _tokenContract;
}
function setOwner(address newOwner) public onlyRegistrar {
require(newOwner != 0);
previousOwner = owner; // This allows contracts to check who sent them the ownership
owner = newOwner;
emit OwnerChanged(newOwner);
}
function setRegistrar(address newRegistrar) public onlyRegistrar {
registrar = newRegistrar;
}
/**
* @dev Sets the Deed's new balance, returning the difference to the owner
*
* The new balance MUST be lower or equal than the current one
*
* @param newTokenQuantity The new balance in tokens
* @param throwOnFailure Flag to indicate if the token transference should throw or not
**/
function setBalance(uint newTokenQuantity, bool throwOnFailure) public onlyRegistrar onlyActive {
// Check if it has enough balance to set the value
require(tokenQuantity >= newTokenQuantity);
uint diffTokenQuantity = tokenQuantity - newTokenQuantity;
tokenQuantity = newTokenQuantity;
// Send the difference to the owner
require(tokenContract.transfer(owner, diffTokenQuantity) || !throwOnFailure);
}
/**
* @dev Computes and sets the expirationDate from a given date, starting the vigency period
*
* @param startDate Date to calculate the expirationDate from
* @param rentValue The value of the initial rent fee to pay in tokens
**/
function startExpiration(uint startDate, uint rentValue) public onlyRegistrar onlyActive {
require(expirationDate == 0 && startDate <= now); // require expiration hasn't started
require(rentValue <= tokenQuantity);
expirationDate = startDate + VALIDITY;
// transfer the fee to the resource pool address
tokenQuantity = tokenQuantity - rentValue;
require(tokenContract.transfer(RESOURCE_POOL_ADDRESS, rentValue));
}
/**
* @dev Pay the Deed's rent, thus extending the expirationDate and the vigency period
*
* Can only be called when the current date falls within the payment period (3 months)
*
* @param rentValue The value to pay in tokens
**/
function payRent(uint rentValue) public onlyRegistrar onlyActive returns(bool) {
require(canPayRent());
require(tokenContract.transfer(RESOURCE_POOL_ADDRESS, rentValue));
expirationDate = expirationDate + VALIDITY;
return true;
}
/**
* @dev Returns wheter the current date falls within the Deed's rent payment period
**/
function canPayRent() public view returns(bool) {
return expirationDate - RENT_PAYMENT_TIME <= now && now <= expirationDate;
}
/**
* @dev Returns wether the Deed is expired or not
**/
function expired() public view returns(bool) {
return 0 < expirationDate && expirationDate < now;
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
*
* @param refundRatio The amount*1/1000 to refund in tokens
*/
function closeDeed(uint refundRatio) public onlyRegistrar onlyActive {
refundAndDestroy(refundRatio);
}
/**
* @dev Close an expired deed. No funds are returned
**/
function closeExpiredDeed() public onlyActive {
require(expired(), "Deed should be expired");
refundAndDestroy(0);
}
/**
* @dev Internal method which handles fund returns/burning and the Deed's destruction
*
* @param refundRatio The amount*1/1000 to refund in tokens
**/
function refundAndDestroy(uint refundRatio) private onlyActive {
require(refundRatio <= 1000);
active = false;
uint torefund = (1000 - refundRatio) * tokenQuantity / 1000;
require(tokenContract.transfer(RESOURCE_POOL_ADDRESS, torefund));
tokenQuantity -= torefund;
emit DeedClosed();
destroyDeed();
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
*/
function destroyDeed() private {
require(!active);
if (tokenContract.transfer(owner, tokenQuantity)) {
selfdestruct(RESOURCE_POOL_ADDRESS);
}
}
function tokenFallback(address from, uint256 amount, bytes data) public returns (bool) {
return true;
}
}
|
Close a deed and refund a specified fraction of the bid value/
|
function destroyDeed() private {
require(!active);
if (tokenContract.transfer(owner, tokenQuantity)) {
selfdestruct(RESOURCE_POOL_ADDRESS);
}
}
| 1,051,525 |
./full_match/42161/0xe805977D5Fa2f05e2175507a1f8E44Cd3F22972c/sources/code/contracts/oasis/OasisSwapRouter.sol
|
LIBRARY FUNCTIONS
|
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return OasisSwapLibrary.quote(amountA, reserveA, reserveB);
}
| 16,308,718 |
./full_match/97/0x6b352845D9407B3AE6E74d61036EF8b7d3FdB752/sources/contracts/t-rex/compliance/DefaultCompliance.sol
|
See {ICompliance-isTokenAgent}./
|
function removeTokenAgent(address _agentAddress) external override onlyOwner {
require(_tokenAgentsList[_agentAddress], "This Agent is not registered yet");
_tokenAgentsList[_agentAddress] = false;
emit TokenAgentRemoved(_agentAddress);
}
| 5,042,287 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity >=0.4.22 <=0.6.12;
import {WETH9} from '../dependencies/weth/WETH9.sol';
contract WCET9Mocked is WETH9 {
constructor() public {
name = 'Wrapped CET';
symbol = 'WCET';
}
// Mint not backed by CET: only for testing purposes
function mint(uint256 value) public returns (bool) {
balanceOf[msg.sender] += value;
emit Transfer(address(0), msg.sender, value);
}
}
|
Mint not backed by CET: only for testing purposes
|
function mint(uint256 value) public returns (bool) {
balanceOf[msg.sender] += value;
emit Transfer(address(0), msg.sender, value);
}
| 12,800,436 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.